Home > Blockchain >  How to convert dataframe rows to variables in R
How to convert dataframe rows to variables in R

Time:06-15

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.

thanks

CodePudding user response:

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"
  •  Tags:  
  • r
  • Related