R如何进行赋值和引用从字符串转换而来的变量名
R how to make assignments and reference a variable name converted from a string
我的问题嵌入在下面的代码中。
我已经从字符串创建了变量名,我可以为这些变量名(在本例中是一个列表)赋值,但是我不能对列表做任何简单的操作,除非我使用创建的变量名字,我不想这样做。如何对这些列表进行简单操作,例如示例中的 cbind?
id = c(96, 99)
namevector = paste("id.", per, sep = "")
assign(namevector[1],c(2,3))
assign(namevector[2],c(52,53))
cbind(id.96, id.99) # This is the desired answer. How do I get it, without using "id.96" or "id.99"?
#here are ideas that did not work
cbind(namevector[1], namevector[2])
cbind(as.name(namevector[1]), as.name(namevector[2]))
我们可以使用 mget
到 return list
中对象的值,然后 cbind
list
元素到单个数据集do.call
do.call(cbind, mget(namevector))
# id.96 id.99
#[1,] 2 52
#[2,] 3 53
假设 per
是 id
我的问题嵌入在下面的代码中。
我已经从字符串创建了变量名,我可以为这些变量名(在本例中是一个列表)赋值,但是我不能对列表做任何简单的操作,除非我使用创建的变量名字,我不想这样做。如何对这些列表进行简单操作,例如示例中的 cbind?
id = c(96, 99)
namevector = paste("id.", per, sep = "")
assign(namevector[1],c(2,3))
assign(namevector[2],c(52,53))
cbind(id.96, id.99) # This is the desired answer. How do I get it, without using "id.96" or "id.99"?
#here are ideas that did not work
cbind(namevector[1], namevector[2])
cbind(as.name(namevector[1]), as.name(namevector[2]))
我们可以使用 mget
到 return list
中对象的值,然后 cbind
list
元素到单个数据集do.call
do.call(cbind, mget(namevector))
# id.96 id.99
#[1,] 2 52
#[2,] 3 53
假设 per
是 id