How to reshape tabular data to one row per group

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

    To me, this solution seems pretty straightforward

    # split the data frame by type and use unlist, which will provide names
    ld <- lapply(split(d[-1], d[["type"]]), unlist)
    
    # gather all the unique names in the list
    ldNames <- Reduce(unique, lapply(ld, names))
    
    # use the names to index each list element, which makes them
    # all of equal length and suitable for row binding.  
    do.call(rbind, lapply(ld, function(x) x[ldNames]))
    #   x11 x12 x13 x21 x22 x23 x31 x32 x33
    # A   4   7   9   6   4   6   9   1   2
    # B   1   2  NA   3   7  NA   8   9  NA
    

    If the order of the output above is not satisfactory, you can rearrange:

    # save the output from above
    d2 <- do.call(rbind, lapply(ld, function(x) x[ldNames]))
    # reorder the names
    ldNames_sorted <- c(matrix(ldNames, ncol = (ncol(d) - 1), byrow = TRUE))
    
    # apply the new order.
    d2 <- d2[, ldNames_sorted]
    #  x11 x21 x31 x12 x22 x32 x13 x23 x33
    #A   4   6   9   7   4   1   9   6   2
    #B   1   3   8   2   7   9  NA  NA  NA
    

    To add a column for type instead of using row names, one method would be:

    data.frame(type = row.names(d2), d2)
    

提交回复
热议问题