How to reshape tabular data to one row per group

后端 未结 5 1323
轻奢々
轻奢々 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:22

    Variation on @Hack-R's answer:

    A$num <- with(A, ave(as.character(type), type, FUN=seq_along) )
    tmp <- cbind(A[c(1,5)], stack(A[2:4]))
    tmp$time <- paste(tmp$ind, tmp$num, sep=".")
    
    reshape(tmp[c("type","time","values")], idvar="type", timevar="time", direction="wide")
    
    #  type values.x1.1 values.x1.2 values.x1.3 values.x2.1 values.x2.2 values.x2.3 values.x3.1 values.x3.2 values.x3.3
    #1    A           4           7           9           6           4           6           9           1           2
    #4    B           1           2          NA           3           7          NA           8           9          NA
    

    And a dplyr version for fun:

    library(dplyr)
    library(tidyr)
    
    A %>%
      gather(var, value, -type) %>%
      group_by(type,var) %>%
      mutate(time=seq_along(var)) %>% 
      ungroup() %>%
      unite(grpvar, c(time,var) ) %>%
      spread(grpvar, value )
    
    #Source: local data frame [2 x 10]
    #
    #   type  1_x1  1_x2  1_x3  2_x1  2_x2  2_x3  3_x1  3_x2  3_x3
    #  (chr) (int) (int) (int) (int) (int) (int) (int) (int) (int)
    #1     A     4     6     9     7     4     1     9     6     2
    #2     B     1     3     8     2     7     9    NA    NA    NA
    

提交回复
热议问题