简体   繁体   English

按列拆分数据框

[英]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. 但是我想要一个数据帧列表,保留SG信息,并且每个数据帧都包含一列初始数据帧。 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. 当您要将行而不是列分成不同的组时,data.frames的split()更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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