如何从R中的变量名列表中调用变量

时间:2022-05-23 20:25:54

I have of list of variable names.

我有变量名列表。

list = c("smoke", "ptd", "ht", "ui", "racecat", "visit")

I want to make a series of plots like this.

我想制作一系列这样的情节。

plot(low[somevariable=="0"] ~ age[somevariable=="0"])

I'd like to replace somevariable with each of the variable name in the list. For example,

我想用列表中的每个变量名替换somevariable。例如,

plot(low[smoke=="0"] ~ age[smoke=="0"])
plot(low[ptd=="0"] ~ age[ptd=="0"])
......
plot(low[visit=="0"] ~ age[visit=="0"])

I've tried to create a for-loop and use a variety of things to replace somevariable, such as

我试图创建一个for循环并使用各种东西来替换一些变量,例如

list[i], paste(list[i]), substitute(list[i]), parse(list[i])

But none of them works. I would really appreciate some help. Thanks in advance.

但它们都不起作用。我真的很感激一些帮助。提前致谢。

3 个解决方案

#1


1  

You can try:

你可以试试:

for(i in list) {
  print(plot(low[get(i) == 0] ~ low[get(i) == 0]))
}

#2


0  

Here's a trivial example of what you want to do. You can use get to find the relevant named variable:

这是你想要做的一个简单的例子。您可以使用get来查找相关的命名变量:

set.seed(1)
x <- rnorm(100)
y <- rnorm(100)
a <- rnorm(100)
b <- rnorm(100,10)
l <- c('a','b')
# histogram of one variable:
hist(get(l[1]))
# loop of plots more like what you're going for:
for(i in 1:length(l)) plot(y[get(l[i])<2] ~ x[get(l[i])<2])

#3


0  

Find the solution:

找到解决方案:

eval(parse(text=list[i]))

There is another post addressing the same thing:

还有另一篇文章解决了同样的问题:

Getting strings recognized as variable names in R

在R中将字符串识别为变量名

#1


1  

You can try:

你可以试试:

for(i in list) {
  print(plot(low[get(i) == 0] ~ low[get(i) == 0]))
}

#2


0  

Here's a trivial example of what you want to do. You can use get to find the relevant named variable:

这是你想要做的一个简单的例子。您可以使用get来查找相关的命名变量:

set.seed(1)
x <- rnorm(100)
y <- rnorm(100)
a <- rnorm(100)
b <- rnorm(100,10)
l <- c('a','b')
# histogram of one variable:
hist(get(l[1]))
# loop of plots more like what you're going for:
for(i in 1:length(l)) plot(y[get(l[i])<2] ~ x[get(l[i])<2])

#3


0  

Find the solution:

找到解决方案:

eval(parse(text=list[i]))

There is another post addressing the same thing:

还有另一篇文章解决了同样的问题:

Getting strings recognized as variable names in R

在R中将字符串识别为变量名