How can I stack columns per x columns in R

前端 未结 5 625
春和景丽
春和景丽 2021-01-07 14:25

I\'m looking to transform a data frame of 660 columns into 3 columns just by stacking them on each other per 3 columns without manually re-arranging (since I have 660 column

5条回答
  •  温柔的废话
    2021-01-07 14:42

    rbind.data.frame requires that all columns match up. So use setNames to replace the names of the C:D columns:

    rbind( dat[1:2], setNames(dat[3:4], names(dat[1:2]))  )
      A  B
    1 1  4
    2 2  5
    3 3  6
    4 7 10
    5 8 11
    6 9 12
    

    To generalize that to multiple columns use do.call and lapply:

     dat <- setNames( as.data.frame( matrix(1:36, ncol=12) ), LETTERS[1:12])
     dat
    #----
      A B C  D  E  F  G  H  I  J  K  L
    1 1 4 7 10 13 16 19 22 25 28 31 34
    2 2 5 8 11 14 17 20 23 26 29 32 35
    3 3 6 9 12 15 18 21 24 27 30 33 36
    
    
    do.call( rbind, lapply( seq(1,12, by=3), function(x) setNames(dat[x:(x+2)], LETTERS[1:3])   ))
        A  B  C
    1   1  4  7
    2   2  5  8
    3   3  6  9
    4  10 13 16
    5  11 14 17
    6  12 15 18
    7  19 22 25
    8  20 23 26
    9  21 24 27
    10 28 31 34
    11 29 32 35
    12 30 33 36
    

    The 12 would be replaced by 660 and everything else should work.

提交回复
热议问题