Convert columns to rows keeping the name of the column

前端 未结 2 1569
梦如初夏
梦如初夏 2021-01-05 18:23

Is there any way in R to Convert columns to rows keeping the name of the column?

Example input:

A   B
1   1
2   3
3   4
44  5

Outpu

2条回答
  •  星月不相逢
    2021-01-05 18:55

    No need to use reshape2, you can use the stack function from base-R :

    With your.data as your example:

    res <- stack(your.data)
    colnames(res) = c("Number", "Group")
    

    gives you

    > res
      Number Group
    1      1     A
    2      2     A
    3      3     A
    4     44     A
    5      1     B
    6      3     B
    7      4     B
    8      5     B
    

    See also here.


    Benchmarking melt from reshape2 and stack from base on bigger data:

    require(reshape2)
    set.seed(45)
    DF <- data.frame(matrix(sample(20, 1e6, TRUE), ncol=100))
    
    require(microbenchmark)
    microbenchmark(stack(DF), melt(DF), times=100)
    
    Unit: milliseconds
          expr      min       lq   median       uq      max neval
     stack(DF) 157.7084 187.1993 241.8206 251.7132 334.5488   100
      melt(DF) 174.6079 253.1088 261.6234 273.3971 443.9953   100
    

    Seems like stack is faster, but by a margin of 20 milliseconds...

提交回复
热议问题