Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include a variable name in a function call in R?

Tags:

r

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)))
}
like image 818
John Avatar asked Feb 23 '10 08:02

John


3 Answers

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)

like image 157
Marek Avatar answered Nov 15 '22 09:11

Marek


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.

like image 30
mropa Avatar answered Nov 15 '22 09:11

mropa


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

like image 35
hatmatrix Avatar answered Nov 15 '22 08:11

hatmatrix