2

I looked at this solution: R-friendly way to convert R data.frame column to a vector?

but each solution seems to involve manually declaring the name of the vector being created.

I have a large dataframe with about 224 column names. I would like to break up the data frame and turn it into 224 different vectors which preserve their label without typing them all manually. Is there a way to step through the columns in the data frame and produce a vector which has the same name as the column or am I dreaming?

Community
  • 1
  • 1
Jesse_m_m
  • 185
  • 1
  • 9
  • 1
    Why do you think it's necessary to do that. Can't a `with()` statement help you? It would help if you provided some sort of [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) showing exactly what you want. Maybe you're looking for `list2env`? But there are usually more R-like ways to do things. – MrFlick Apr 27 '16 at 02:42
  • 3
    Now all we need is an `eval(parse(text=...))` answer to complete the trifecta of R's most dangerous commands. – Rich Scriven Apr 27 '16 at 03:01
  • I'm thoroughly enjoying the three "bad" ideas suggested. – Adam Quek Apr 27 '16 at 03:04

4 Answers4

6

I think it's a bad idea but this would work (using mtcars data set):

list2env(mtcars, .GlobalEnv)
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
3

attach is another dangerous command that people use to be able to access the columns of a data frame directly with their names. If you don't know why it's dangerous, though, don't do it.

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142
3

Here's another bad idea:

for(i in names(mtcars)) assign(i, mtcars[,i])
Adam Quek
  • 6,973
  • 1
  • 17
  • 23
3

Just for Richard:

for (x in names(mtcars))
    eval(parse(text=paste(x, '<- c(', paste(mtcars[[x]], collapse=',') ,')')))
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112