How to reshape tabular data to one row per group

后端 未结 5 1318
轻奢々
轻奢々 2020-12-21 23:57

I am an R (and coding novice) and I am looking for a way to reconfigure Table A show below into Table B.

Table A:

type   x1  x2  x3  
A      4   6            


        
5条回答
  •  伪装坚强ぢ
    2020-12-22 00:17

    a <- data.frame(type=c("A", "A","A", "B", "B"), x1 = c(4,7,9,1,2),x2=c(6,4,6,3,7),
                   x3 = c(9,1,2,8,9))
    
    library(dplyr)
    tmp <-
    a %>% 
      group_by(type) %>%
      summarise(no_rows = length(type))
    
    for(i in unique(a$type)){
      n <- max(tmp$no_rows) - nrow(a[a$type == i,])
      nn <- nrow(a)
      if(n > 0){
        for(ii in 1:n){
          a[nn+ii,] <- c(i,NA,NA,NA)
        }    
      }
    
    }
    
    a <- a[order(a$type),]
    a$timevar <- seq(1:max(tmp$no_rows) )
    
    b<-reshape(a,timevar="timevar",idvar="type",direction="wide",drop = F)
    b
    
      type x1.1 x2.1 x3.1 x1.2 x2.2 x3.2 x1.3 x2.3 x3.3
    1    A    4    6    9    7    4    1    9    6    2
    4    B    1    3    8    2    7    9   
    

提交回复
热议问题