I have the following dataframe:
df <- data.frame(a = 1, b = 2, c = 3)
I want to convert it to three named vectors:
a <- 1
b <- 2
c <- 3
How can I do this programmatically? tidyverse
solutions especially appreciated.
CodePudding user response:
You could do something like this (though @MartinGal gives a better method). We can convert each column to a list, then flatten
to just have a named vector, then can save to the global environment.
library(tidyverse)
list2env(flatten(apply(df, 2, function(x) as.list(x))), envir = .GlobalEnv)
CodePudding user response:
Another possible solution (you should follow @MartinGal's approach though):
list2env(lapply(df, \(x) `<-`(names(x), x)),.GlobalEnv)
a
#> [1] 1
b
#> [1] 2
c
#> [1] 3
CodePudding user response:
df[,'a']
also works
Refer extract operator