简体   繁体   中英

Splitting a dataframe by columns

I want to split my dataframe by columns. Sounds trivial, but i didnt really succeed so far. Here is what i have come up with:

SG <- data.frame(num = 1:26, let = letters, LET = LETTERS)
SG <- lapply(SG, function(x) split(x, colnames(SG)))
str(SG)

List of 3
 $ num:List of 3
 $ let:List of 3
 $ LET:List of 3

I have successfully converted my dataframe into a list of lists. But i would like to have a list of dataframes, preserving the rowname info from SG , and each one of them containing one column of the initial dataframe. Is that possible?

Thank you!

This should work, row names are preserved. It returns a list of data frames:

SG <- lapply(SG, data.frame)

str(SG)
List of 3
 $ num:'data.frame':    26 obs. of  1 variable:
  ..$ X..i..: int [1:26] 1 2 3 4 5 6 7 8 9 10 ...
 $ let:'data.frame':    26 obs. of  1 variable:
  ..$ X..i..: Factor w/ 26 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ LET:'data.frame':    26 obs. of  1 variable:
  ..$ X..i..: Factor w/ 26 levels "A","B","C","D",..: 1 2 3 4 5 6 7 8 9 10 ...

You can use

lapply(colnames(SG), function(x) SG[,x,drop=F])

which returns an object with the structure

List of 3
 $ :'data.frame':   26 obs. of  1 variable:
  ..$ num: int [1:26] 1 2 3 4 5 6 7 8 9 10 ...
 $ :'data.frame':   26 obs. of  1 variable:
  ..$ let: Factor w/ 26 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ :'data.frame':   26 obs. of  1 variable:
  ..$ LET: Factor w/ 26 levels "A","B","C","D",..: 1 2 3 4 5 6 7 8 9 10 ...

In this case we are just subsetting. split() for data.frames is better when you want to separate the rows, not columns, into different groups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM