我想在 R Studio 中重新排列我的数据(排序和 cbind)

I want to rearrange my data in R Studio (sorting and cbind)

如果我有如下数据框:

R/C DD  CC1 CC2
RR1 a   36  37 
RR1 b   21  22 
RR1 c   24  25 
RR1 d   196 198 
RR2 e   37  38 
RR2 f   17  17 
RR2 g   16  16 
RR2 h   48  51 
RR3 i   89  90 
RR3 j   79  80 
RR3 k   26  26 
RR3 h   48  51 

共有三种不同的行; RR1、RR2 和 RR3。基于此,我想重新排列如下:

我必须排序并使用 cbind 吗?

您可以 splitcbind

建议不要有同名的列,下面的答案为每列添加前缀。

do.call(cbind, split(df, df$`R/C`))

#  RR1.R/C RR1.DD RR1.CC1 RR1.CC2 RR2.R/C RR2.DD RR2.CC1 RR2.CC2 RR3.R/C RR3.DD RR3.CC1 RR3.CC2
#1     RR1      a      36      37     RR2      e      37      38     RR3      i      89      90
#2     RR1      b      21      22     RR2      f      17      17     RR3      j      79      80
#3     RR1      c      24      25     RR2      g      16      16     RR3      k      26      26
#4     RR1      d     196     198     RR2      h      48      51     RR3      h      48      51

数据

df <- structure(list(`R/C` = c("RR1", "RR1", "RR1", "RR1", "RR2", "RR2", 
"RR2", "RR2", "RR3", "RR3", "RR3", "RR3"), DD = c("a", "b", "c", 
"d", "e", "f", "g", "h", "i", "j", "k", "h"), CC1 = c(36L, 21L, 
24L, 196L, 37L, 17L, 16L, 48L, 89L, 79L, 26L, 48L), CC2 = c(37L, 
22L, 25L, 198L, 38L, 17L, 16L, 51L, 90L, 80L, 26L, 51L)), 
class = "data.frame", row.names = c(NA, -12L))