Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (50.2k points)
recategorized by

Let's say, for instance, I am having the following data frame and from that, I want to rearrange that like the below image:

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 

The desired structure would be:

enter image description here

Can you please guide me if I have to sort that data and use cbind?

1 Answer

0 votes
by (108k points)

For achieving that data structure, first, you have to perform the splitting and then use the cbind():

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

The 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))

If you are a beginner and want to know more about R then do check the R programming tutorial

Browse Categories

...