开发者

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

开发者 https://www.devze.com 2022-12-21 11:43 出处:网络
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 tr

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 t开发者_如何学编程hem 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)))
}


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)


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消