Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading