简体   繁体   English

如何在 R 中使用 get() 来访问带有另一个变量的变量?

[英]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.

相关问题 如何获取 R 中另一个变量的变量总数? 这两个变量都是非数字的 - How do I get the aggregate number of a variable against another variable in R? Both these variables are non-numeric 如何根据 R 中的另一个变量创建条件变量? - How do I create a conditional variable based on another variable in R? 如何从另一个输出访问变量 - How do I access a variable from another output R:如何在“ by”是变量的函数中使用聚合? - R: How do I use aggregate in a function where the 'by' is a variable? 如何在 R Shiny 中使用 NULL 值作为变量调用 - How do I use the NULL Value as a variable call in R Shiny 如何在R中使用宏变量? (类似于SAS中的%LET) - How do I use a macro variable in R? (Similar to %LET in SAS) R - 如何让变量在 for 循环中遍历 i? - R - How do you get a variable to iterate through i in a for loop? 如何根据 R 中另一个变量的值更改变量中的值? - How do I change a value within a variable based on the value of another variable in R? 如何在 R 中创建变量来计算另一个变量的一个变量的值的数量? - How do I create variables in R that count the number of values of one variable by another variable? 如何获取分组变量的计数并在 R 中添加另一个具有计数的变量? - How to get the counts of a grouped variable and add another variable with counts in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM