Search code examples
rtidyverse

Convert dataframe into named vectors based on column names


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.


Solution

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