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.
We split
the string, get the value with mget
and cbind
the list
of vector
s 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]]))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With