Useing r, have a vector containing instructions to form a dataframe, how can I use that vector to form a dataframe?

Say I have the instructions to create a df as such:

data.frame(Tech = c(rep('Cell',20),rep('Therapy',20)),
Gene1 = runif(40, 0, 30),
Gene2 = runif(40, 10, 25),
Gene3 = runif(40, 5, 50))

But this is stored in a vector (FYI, this is because I have imported it from a local HTML file):

dfcode<-"Tech = c(rep('Cell',20),rep('Therapy',20)),
    Gene1 = runif(40, 0, 30),
    Gene2 = runif(40, 10, 25),
    Gene3 = runif(40, 5, 50)"

Is there some way I can generate the dataframe useing the dfcode vector (i.e. without simply copy and pasting it)?

My attempts have revolved around something like below, which invariably gets me a 1×1 df:

df<-data.frame(dfcode)

Thanks.

>Solution :

You can use eval(parse(text)):

eval(parse(
    text = paste0("df <- data.frame(", dfcode, ")")
))

head(df)
#   Tech      Gene1    Gene2    Gene3
# 1 Cell  3.7633360 20.17803 37.31242
# 2 Cell  1.5634394 18.29588 17.87976
# 3 Cell 12.0542608 24.21807 20.02645
# 4 Cell  0.3588181 18.06053 40.62191
# 5 Cell 28.1320578 17.21433 31.36131
# 6 Cell 24.2420675 24.73983 30.73401

There are security concerns about doing this though, and it is slower than running code natively.

Leave a Reply