[英]How do I refer to a data frame element with strings in R?
n <- 1
sn <- "n"
get (sn)
This will work.这将起作用。 However, the following won't work:
但是,以下操作不起作用:
n <- as.data.frame(matrix(1,2,2))
sn <- "n$V1"
get (sn)
How should I make this work?我应该如何使这项工作?
eval(parse(text=sn))
works.作品。 Thanks.
谢谢。
I am doing that because there are 1000 variables in the dataframe and I need a variable passed from a function to tell which variable out of the 1000 variables that I need to work further on.我这样做是因为数据框中有 1000 个变量,我需要从函数传递一个变量来告诉我需要进一步处理 1000 个变量中的哪个变量。
You almost certainly want to pass just the name of the column within the data frame, then use [[
-indexing to retrieve the vector you want:您几乎可以肯定只想传递数据框中列的名称,然后使用
[[
-indexing 来检索您想要的向量:
n <- as.data.frame(matrix(1,2,2))
sn <- "V1"
n[[sn]]
## [1] 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.