tags:

views:

189

answers:

4

I'm trying to change the name of a variable that is included inside a for loop and function call. In the example below, I'd like column_1 to be passed to the plot function, then column_2 etc. I've tried using do.call, but it returns "object 'column_j' not found". But object column_j is there, and the plot function works if I hard-code them in. Help much appreciated.

for (j in 2:12) {
    column_to_plot = paste("column_", j, sep = "")
    do.call("plot", list(x, as.name(column_to_plot)))
}
+1  A: 

You can do it without the paste() command in your for loop. Simply assign the columns via the function colnames() in your loop:

column_to_plot <- colnames(dataframeNAME)[j]

Hope that helps as a first kludge.

mropa
+1  A: 

Here is one way to do it:

tmp.df <- data.frame(col_1=rnorm(10),col_2=rnorm(10),col_3=rnorm(10))
x <- seq(2,20,by=2)
plot(x, tmp.df$col_1)
for(j in 2:3){
  name.list <- list("x",paste("col_",j,sep=""))
  with(tmp.df, do.call("lines",lapply(name.list,as.name))) }

You can also do colnames(tmp.df)[j] instead of paste(..) if you'd like.

Leo Alekseyev
+3  A: 

I do:

x <- runif(100)
column_2 <-
    column_3 <-
    column_4 <-
    column_5 <-
    column_6 <-
    column_7 <-
    column_8 <-
    column_9 <-
    column_10 <-
    column_11 <-
    column_12 <- rnorm(100)

for (j in 2:12) {
    column_to_plot = paste("column_", j, sep = "")
    do.call("plot", list(x, as.name(column_to_plot)))
}

And I have no errors. Maybe you could provide hard-code which (according to your question) works, then will be simpler to find a reason of the error.

(I know that I can generate vectors using loop and assign, but I want to provide clear example)

Marek
I too could not reproduce the original poster's problem.
Jyotirmoy Bhattacharya
+1  A: 

Are you trying to retrieve an object in the workspace by a character string? In that case, parse() might help:

for (j in 2:12) {
    column_to_plot = paste("column_", j, sep = "")
    plot(x, eval(parse(text=column_to_plot)))
}

In this case you could use do.call(), but it would not be required.

Edit: wrapp parse() in eval()

Stephen
Stephen, thanks, I was curious about the parse function so I tried your example, but it did not work for me. I also tried with parse(text=column_to_plot)[[1]]) to get just the element I wanted to plot, but it says 'x' and 'y' lengths differ. However, plot(x, column_2) works in this case.
John
Ah, sorry! See edit above... (wrap the call to parse() in eval())
Stephen