好吧 - 这看起来主要是你想要的。通过阅读帮助文件,这似乎应该做你想做的事:
reshape(df, idvar = c("c1", "c2"), timevar = c("gr", "subgr")
, direction = "wide")
c1 c2 val.c(1, 2, 1, 2) val.c(1, 1, 2, 2)
1 1 1 NA NA
5 1 2 NA NA
9 2 1 NA NA
13 2 2 NA NA
我无法完全解释为什么它会显示 NA 值。但是,也许帮助页面中的这一点解释了:
timevar
the variable in long format that differentiates multiple records from the same
group or individual. If more than one record matches, the first will be taken.
我最初认为这意味着如果您给它的列名有歧义,R 将使用它的部分匹配功能,但也许不是?接下来,我尝试将grand组合subgr成一个列:
df$newcol <- with(df, paste("gr.", gr, "subgr.", subgr, sep = ""))
让我们再试一次:
reshape(df, idvar = c("c1", "c2"), timevar = "newcol"
, direction = "wide", drop= c("gr","subgr"))
c1 c2 val.gr.1subgr.1 val.gr.2subgr.1 val.gr.1subgr.2 val.gr.2subgr.2
1 1 1 1 2 3 4
5 1 2 5 6 7 8
9 2 1 9 10 11 12
13 2 2 13 14 15 16
快!我无法解释或弄清楚如何使它不附加val.到列名,但我会让你自己弄清楚。我确定它在某处的帮助页面上。它还将组的顺序与您要求的顺序不同,但数据似乎是正确的。
FWIW,这是一个解决方案reshape2
> dcast(c1 + c2 ~ gr + subgr, data = df, value.var = "val")
c1 c2 1_1 1_2 2_1 2_2
1 1 1 1 3 2 4
2 1 2 5 7 6 8
3 2 1 9 11 10 12
4 2 2 13 15 14 16
尽管您仍然必须清理列名。