0

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 1x1 df:

df<-data.frame(dfcode)

Thanks.

ZaiShaMo
  • 3
  • 3
  • well... your ```dfcode``` is defined to contain one text string because everything right of the ```<-``` is between " " – Omniswitcher Jul 27 '22 at 14:24

1 Answers1

0

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.

SamR
  • 8,826
  • 3
  • 11
  • 33