Frage

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,

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

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.

War es hilfreich?

Lösung

You can try:

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

Andere Tipps

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

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])

Find the solution:

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

There is another post addressing the same thing:

Getting strings recognized as variable names in R

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top