0

If I have a data frame as follows:

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 

There are three different kinds of rows; RR1, RR2 and RR3. Based on that I want to rearrange this like:

enter image description here

Do I have to sort and use cbind?

1 Answers1

1

You can split and cbind.

It is advised not to have a column with same names, the answer below adds prefix to each column.

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

data

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))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213