Using the contents of a string as an argument to a function in R

Is there a way to use a string as an argument to a function. 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 line that is "df1, df2, df3".

> x <- 'df1, df2, df3'

Is there a way to use the contents of a string in cbind? For example, I need a way to do the following ...

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

In fact, he does this ...

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

Is there a way to trick the cbind function to view the contents of a string?

Any help is greatly appreciated.

+4
source share
3 answers

We are a splitstring, get the value mgetand cbind listof vectorwithdo.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, do.call(cbindwe can also convert todata.frame

data.frame(mget(strsplit(x, ', ')[[1]]))
+5
source

, @akrun, , .

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
+1

Another possibility:

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

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


All Articles