Jesse_m_m
Jesse_m_m

Reputation: 205

R friendly way to convert lots of R data frame columns to lots of vectors

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?

Upvotes: 2

Views: 220

Answers (4)

Matthew Lundberg
Matthew Lundberg

Reputation: 42629

Just for Richard:

for (x in names(mtcars))
    eval(parse(text=paste(x, '<- c(', paste(mtcars[[x]], collapse=',') ,')')))

Upvotes: 3

Adam Quek
Adam Quek

Reputation: 7153

Here's another bad idea:

for(i in names(mtcars)) assign(i, mtcars[,i])

Upvotes: 3

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37734

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.

Upvotes: 3

Tyler Rinker
Tyler Rinker

Reputation: 109844

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

list2env(mtcars, .GlobalEnv)

Upvotes: 6

Related Questions