我有这样的数据:
A B
1 10
1 20
1 30
2 10
2 30
2 40
3 20
3 10
3 30
4 20
4 10
5 10
5 10我想建立一个这样的应急表:
10 20 30 40
10 1 3 2 0
20 3 0 2 0
30 2 2 0 0
40 0 0 0 0意思:根据A栏,在特定的列中,B标记+1的每两个值。
你能帮我做这个吗?
发布于 2015-07-20 19:26:16
这是一个非常丑陋的答案,使用来自图像的数据,因为我已经花了太多的时间在你的问题上。一般来说,让您的结果取决于变量的顺序是不实际的。
A <- rep(c(1:4),c(3,2,3,3))
B <- c(10,10,30,10,20,30,20,10,10,20,30)
data <- data.frame(cbind(A,B))
#split by A
library(plyr)
data2 <- ddply(data,.(A),function(x){
combined_pairs <- cbind(x$B[-nrow(x)],
x$B[-1])
#return data where first is always lowest
smallest <- apply(combined_pairs,MARGIN=1,
FUN=min)
largest <- apply(combined_pairs,MARGIN=1,
FUN=max)
return(data.frame(small=smallest,large=largest))
})
library(reshape2)
result <- dcast(small~large,data=data2,
fun.aggregate=length)
> result
small 10 20 30
1 10 1 3 1
2 20 0 0 2如果你还需要的话,我想你可以自己添加空行。
https://stackoverflow.com/questions/31451129
复制相似问题