Tom Danielson
Tom Danielson

Reputation: 43

using the content of a string as a function argument in 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.

Upvotes: 4

Views: 59

Answers (3)

moodymudskipper
moodymudskipper

Reputation: 47320

Another possibility:

eval(parse(text=paste('cbind(',x,')')))
#      df1 df2 df3
# [1,]   1  11  21
# [2,]   2  12  22
# [3,]   3  13  23

Upvotes: 1

Alex P
Alex P

Reputation: 1494

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

Upvotes: 1

akrun
akrun

Reputation: 887118

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

Upvotes: 5

Related Questions