neuron
neuron

Reputation: 2079

How to separate each column in a data frame and make each column into its own new data set

The title of this question may have been a bit confusing, so let me give a bit more detail. I apologize in advance if there are flaws in my terminology. So here is an example of my data frame

a b c d e
1 4 2 7 8
2 4 3 7 1
4 3 5 9 3

So what I would like to do is make each column it's own dataset. I know you can do something like a <- df[c(1)] b <- df[c(2)] etc.. My real data frame has thousands of columns, so having to type that out is going to get annoying. I was wonder if there is a quicker way to do this? Ideally, I would like the new data sets to have the same name as the column, and I'm not quite sure how to go about doing that. I know there will be thousands of data sets but I have a computer that can handle it

Upvotes: 0

Views: 55

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47350

You can use list2env, but think twice, probably you're better off keeping things as structured as possible:

df <- head(iris)
list2env(df,envir = .GlobalEnv)
Species
# [1] setosa setosa setosa setosa setosa setosa
# Levels: setosa versicolor virginica

Or to keep them as one column data.frames:

list2env(setNames(lapply(names(df), function(x) df[x]),names(df)),
  envir = .GlobalEnv)
Species
#   Species
# 1  setosa
# 2  setosa
# 3  setosa
# 4  setosa
# 5  setosa
# 6  setosa

Upvotes: 1

Related Questions