0

I have a dataframe and would like to turn the values into variables.

I've tried using as.numeric(unlist...) to pull them out one by one (it's not a big list), but I'm looking for a better way.

This is my data

dataframe = structure(list(V1 = c(564.58, 7834.1, 134.2), file = structure(c(2L, 
1L, 3L), .Label = c("Blue", "Red", "Yellow"), class = "factor")), class = "data.frame", row.names = c(NA, 
-3L))

I'm looking to get this:

Red = 564.58
Blue = 7834.1
Yellow = 134.2

Can anyone suggest a better way to do this?

nicshah
  • 345
  • 1
  • 8
  • 1
    Do you need `setNames(dataframe$V1, dataframe$file)` OR `split(dataframe$V1, dataframe$file)` ? – Ronak Shah Jul 12 '19 at 04:13
  • I can split them, but I can't assign them as individual variables (short of going through and matching them with a loop). – nicshah Jul 12 '19 at 04:18
  • 1
    you can use `assign` to convert them to individual variables but usually it is recommended to keep variables in a list rather than individual ones. – Ronak Shah Jul 12 '19 at 04:22

1 Answers1

2

The following should work. Put your values V1 in a list with as.list, set the names to file using setNames, and then turn the list elements into variables in the global environment using list2env:

list2env(setNames(as.list(df$V1), df$file), .GlobalEnv)

Having answered, I should also mention that doing this kind of thing is frequently discouraged. Exploding vectorized data to pollute your environment with lots of variables offers very few, if any, advantages, but there are a number of disadvantages. The discussion about assign also applies to list2env. You can read about it here.

  • 1
    Thanks - appreciate the link to the discussion. I've only got a very small list and need to patch this data in. – nicshah Jul 12 '19 at 04:43