从宽到长重塑不整齐和不平衡的数据集

时间:2016-09-27 06:00:42

标签: r reshape

我有一个如下所示的数据集(数据):

ID,ABC.BC,ABC.PL,DEF.BC,DEF.M,GHI.PL
SB0005,C01,D20,C01a,C01b,D20
BC0013,C05,D5,C05a,NA,D5

我想从宽到长格式重塑它以获得类似的东西:

ID,FC,Type,Var
SB0005,ABC,BC,C01
SB0005,ABC,PL,D20
SB0005,DEF,BC,C01a
SB0005,DEF,M,C01b
SB0005,GHI,PL,D20
BC0013,ABC,BC,C05
BC0013,ABC,PL,D5
BC0013,DEF,BC,C05a
# BC0013,DEF,M,NA (This row need not be in the dataset as I will remove it later)
BC0013,GHI,PL,D5

通常的重塑包不起作用,因为数据集不平衡。我也尝试过splitstackshape的Reshape,但它没有给我我想要的东西。

library(splitstackshape)
vary <- grep("\\.BC$|\\.PL$|\\.M$", names(data))
stubs <- unique(sub("\\..*$", "", names(data[vary])))
Reshape(data, id.vars=c("ID"), var.stubs=stubs, sep=".")

ID,time,ABC,DEF,GHI
SB0005,1,C01,C01a,D20
BC0013,1,C05,C05a,D5
SB0005,2,D20,C01b,NA
BC0013,2,D5,NA,NA
SB0005,3,NA,NA,NA
BC0013,3,NA,NA,NA

感谢任何建议,谢谢!

按要求提供dput(data)的输出

structure(list(ID = structure(c(2L, 1L), .Label = c("BC0013", 
"SB0005"), class = "factor"), ABC.BC = structure(1:2, .Label = c("C01", 
"C05"), class = "factor"), ABC.PL = structure(1:2, .Label = c("D20", 
"D5"), class = "factor"), DEF.BC = structure(1:2, .Label = c("C01a", 
"C05a"), class = "factor"), DEF.M = structure(1:2, .Label = c("C01b", 
"NA"), class = "factor"), GHI.PL = structure(1:2, .Label = c("D20", 
"D5"), class = "factor")), .Names = c("ID", "ABC.BC", "ABC.PL", 
"DEF.BC", "DEF.M", "GHI.PL"), row.names = c(NA, -2L), class = "data.frame")

1 个答案:

答案 0 :(得分:3)

您需要先将数据重新整形为长格式,然后将变量列吐出到列中。使用splitstackshape即可:

library(splitstackshape) # this will also load 'data.table' from which the 'melt' function is used
cSplit(melt(mydf, id.vars = 'ID'), 
       'variable', 
       sep = '.', 
       direction = 'wide')[!is.na(value)]

导致:

                          ID value variable_1 variable_2
1:                    SB0005   C01        ABC         BC
2:                    BC0013   C05        ABC         BC
3:                    SB0005   D20        ABC         PL
4:                    BC0013    D5        ABC         PL
5:                    SB0005  C01a        DEF         BC
6:                    BC0013  C05a        DEF         BC
7:                    SB0005  C01b        DEF          M
8:                    SB0005   D20        GHI         PL
9:                    BC0013    D5        GHI         PL

tidyr的替代方案:

library(tidyr)
mydf %>% 
  gather(var, val, -ID) %>% 
  separate(var, c('FC','Type')) %>% 
  filter(!is.na(val))