如何分配给R中变量值的names()属性 [英] how to assign to the names() attribute of the value of a variable in R

查看:13
本文介绍了如何分配给R中变量值的names()属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 中,assign('x',v)"将名称为 'x' 的对象设置为 v.将 'x' 替换为将文本函数应用于变量 x 的结果.然后分配"显示它的价值.

In R, "assign('x',v)" sets the object whose name is 'x' to v. Replace 'x' by the result of applying a text function to a variable x. Then "assign" shows its worth.

很遗憾,assign(paste('names(','x',')',sep=''),v)"失败了.所以如果 'x' 是一个变量 x,我可以设置它的值,但我不能给它的元素命名.

Unfortunately, "assign(paste('names(','x',')',sep=''),v)" fails. So if 'x' is a variable x, I can set its value, but I can't give it names for its elements.

可以解决这个问题吗?也许是解析评估技巧?谢谢.

Can one work around this? a parse-eval trick maybe? Thanks.

推荐答案

在您提出问题的表单中,无需分配名称.如果你 x 存在,那么你执行 names(x) <- v.这是正确的做法.

In the form you ask question there is no need to assign names. If you x exists then you do names(x) <- v. This is right way to do this.

如果您的变量名未知(即动态创建),那么您可以使用 substitute

If your variable name is unknown (i.e. dynamically created) then you could use substitute

nm <- "xxx" # name of your variable
v <- 1:3 # value
assign(nm,v) # assign value to variable

w <- c("a","b","c") # names of variable
eval(substitute(names(x)<-w, list(x=as.symbol(nm))))
# Result is
str(xxx)
# Named int [1:3] 1 2 3
# - attr(*, "names")= chr [1:3] "a" "b" "c"

但是如果你必须做这种技巧,那你的代码就有问题了.

But if you must do this kind of tricks there is something wrong with you code.

这篇关于如何分配给R中变量值的names()属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆