1

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.

5
  • (1) It this really your data frame (since your code creates a - imho - really broken df)? (2) If your actual data.frame is data.frame(a = 1, b = 2, c = 3) I don't think you really want to convert it into three vectors, since you basically have them already (df[["a"]] for example). Commented Apr 15, 2022 at 22:17
  • You're right that the data frame was incorrect, I have fixed it. But df[["a"]] doesn't get me what I want, which is to achieve the specified outcomes programmatically (i.e., without typing a command for each column). Commented Apr 15, 2022 at 22:28
  • May I ask what you are trying to do programmatically? I'm still convinced you don't need a vector named a and can go with df["a"] or in a tidyverse way with a curly-curly or bang-bang construct. Commented Apr 15, 2022 at 22:31
  • I want some named vectors of length 1 to hold values that I can use in functions (e.g., rnorm(10,0,a). Commented Apr 15, 2022 at 22:34
  • 2
    In this example rnorm(10,0,df[["a"]]) should work Commented Apr 15, 2022 at 22:36

3 Answers 3

1

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) 
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

0

df[,'a'] also works

Refer extract operator

1 Comment

df[,'a'] doesn't get me what I want, which is to achieve the specified outcomes programmatically (i.e., without typing a command for each column).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.