How to include variable name in function call in R?

I am trying to change the name of a variable that is included inside a for loop and function call. In the example below, I would like to pass column_1 to the plot function, then column_2, etc. I tried using do.call, but it returns "object" column_j "not found". But there is a column_j object, and the plot function works if I hardcode them. Help evaluate.

for (j in 2:12) { column_to_plot = paste("column_", j, sep = "") do.call("plot", list(x, as.name(column_to_plot))) } 
+4
source share
4 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 mistakes. Perhaps you can provide hard code that (according to your question) works, then it will be easier to find the cause of the error.

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

+6
source

You can do this without the paste() command in a for loop. Just assign columns through the colnames() function in your loop:

 column_to_plot <- colnames(dataframeNAME)[j] 

Hope this helps as a first kludge.

+2
source

Are you trying to get an object in the workspace using a character string? In this case, parse () may 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 can use do.call (), but this is not required.

Edit: wrapp parse () in eval ()

+2
source

Here is one way to do this:

 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 pasting (..) if you want.

+1
source

Source: https://habr.com/ru/post/1302104/


All Articles