Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the content of a string as a function argument in R

Tags:

r

Is there a way to use a string as a function argument. In my example, I have three vectors and I can use cbind to combine them.

> df1<-1:3
> df2<-11:13
> df3<-21:23
> 
> cbind(df1, df2, df3)
     df1 df2 df3
[1,]   1  11  21
[2,]   2  12  22
[3,]   3  13  23

Suppose I have a string that is "df1, df2, df3".

> x <- 'df1, df2, df3'

Is there a way to use the content of the string in the cbind? For example, I would like a way to do the following...

> cbind(x)
     df1 df2 df3
[1,]   1  11  21
[2,]   2  12  22
[3,]   3  13  23

In reality, it does this...

> cbind(x)
     x              
[1,] "df1, df2, df3"

Is there a way to trick the cbind function into seeing the content of the string?

Any help is greatly appreciated.

like image 822
Tom Danielson Avatar asked Mar 07 '23 18:03

Tom Danielson


2 Answers

We split the string, get the value with mget and cbind the list of vectors with do.call

do.call(cbind, mget(strsplit(x, ', ')[[1]]))
#     df1 df2 df3
#[1,]   1  11  21
#[2,]   2  12  22
#[3,]   3  13  23

Or instead of do.call(cbind, we can also convert to data.frame

data.frame(mget(strsplit(x, ', ')[[1]]))
like image 157
akrun Avatar answered Mar 10 '23 14:03

akrun


more libraries and more code than @akrun's answer, but I did it and so I'm posting it.

library(stringr)
library(dplyr)

df1<-1:3
df2<-11:13
df3<-21:23
x <- 'df1, df2, df3'

x2 <- str_split(x, ", ", simplify=TRUE)
x3 <- lapply(x2, function(i){as.data.frame(eval(parse(text=i)))})
x4 <- bind_cols(x3)
names(x4) <- x2
like image 23
Alex P Avatar answered Mar 10 '23 13:03

Alex P