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

How to convert dataframe rows to variables in R

If I have a 2 column, 4 row data frame such as:

structure(list(var = c("url.loc", "radius", "jt", "post.age"), 
value = c("london", "25", "fulltime", "7")), row.names = c(NA, 
-4L), spec = structure(list(cols = list(var = structure(list(), class = c("collector_character", 
"collector")), value = structure(list(), class = c("collector_character", 
"collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x60000323fee0>, class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"))

… how would I go about converting this to 4 variables so the result would be the same as:

url.loc <- "london"
radius <- "25"
jt <- "fulltime"
post.age <- "7"

I can think of using assign and a loop, but I’m thinking there’s a more elegant way, perhaps using NSE.

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

thanks

>Solution :

We may create a named list and use list2env

library(tibble)
list2env(as.list(deframe(df1)), .GlobalEnv)

-checking

> url.loc
[1] "london"
> radius
[1] "25"

A compact option is with %=% from collapse

library(collapse)
df1$var %=% df1$value

-checking

> url.loc
[1] "london"
> radius
[1] "25"
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