我设法获得了以下格式的数据:
run type1
data1 12
data2 13
run type2
data1 14
data2 15
...我要:
run data1 data2
type1 12 13
type2 14 15
...我试过投[投],但没有用。有什么建议吗?
样本数据:
data.frame(matrix(c("run","type1","data1",12,"data2",13,"run","type2","data1",14,"data3",15), ncol=2, byrow=T))发布于 2014-07-08 19:05:50
这是我的建议:
cast.runs <- function(d) {
isrun <- d[[1]]=="run"
whichrun <- which(isrun)
lens <- diff(c(whichrun, nrow(d)+1))
runlabels <- inverse.rle(list(lengths=lens, values=d[[2]][whichrun]))
return(cbind(run=runlabels, d)[!isrun,])
}此函数将产生合适的长格式,然后您可以根据您认为合适的情况重铸它:
runlabels X1 X2
2 type1 data1 12
3 type1 data2 13
5 type2 data1 14
6 type2 data3 15毫不奇怪,我从识别run行开始。我计算了每一次运行有多少行,包括标题行。该代码是受this answer启发的。接下来,我多次重复每个运行标签,最后删除标题行。
转换此输出的一种可能方法是使用来自dcast包的reshape2函数:
> dcast(cast.runs(d), run ~ X1)
Using X2 as value column: use value.var to override.
run data1 data2 data3
1 type1 12 13 <NA>
2 type2 14 <NA> 15https://stackoverflow.com/questions/24637921
复制相似问题