[英]How do I use get() in R to access a variable with another variable?
I have a loop which is running over a vector containing names of a few tens of dataframes that are in my environment.我有一个循环运行在一个向量上,该向量包含我环境中的几十个数据帧的名称。 On each iteration, I want to access the dataframe using the name, and access a specific column within it.在每次迭代中,我想使用名称访问 dataframe,并访问其中的特定列。 As I understand it, the best way to access a variable with a string is using get()
.据我了解,使用字符串访问变量的最佳方法是使用get()
。
But when I try and do this (with name being a variable containing the string "first.name"
):但是当我尝试这样做时(名称是一个包含字符串"first.name"
的变量):
get(column.name, name)
I get the error:我得到错误:
Error in as.environment(pos) : no item called "first.name" on the search list
It does work if I try to run:如果我尝试运行它确实有效:
get(column.name, first.name)
So, assuming that get()
is the right function for this, what am I doing wrong?所以,假设get()
是正确的 function ,我做错了什么?
Reproduceable example:可重现的例子:
my.df <- as.data.frame(x = seq(1:10), y = rnorm(10))
name <- "my.df"
get("x",name)
We may need to use我们可能需要使用
get(name)[[column.name]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.