您用文字描述的内容和您在预期输出中显示的内容不一致。特别是,根据您的输入,计算y
的唯一值应该是2和1,而不是3和2。与书面说明会:
DF <- data.frame(t=c(1,1,1,2,2), x=c(1,1,1,1,2), y=c(3,3,2,2,2))
library("plyr")
ddply(DF, .(t), function(DF) {
data.frame(cnt=length(DF$t), colwise(function(x) {length(unique(x))})(DF))
})
或者,如果你想获得真正的功能看:
library("functional")
ddply(DF, .(t), function(DF) {
data.frame(cnt=length(DF$t), colwise(Compose(unique, length))(DF))
})
或完全与功能模式过分去:
merge(ddply(DF, .(t), summarise, cnt=length(t)),
ddply(DF, .(t), colwise(Compose(unique, length))))
这些都不给你要求的列名;而不是cux
它是x
。但是,他们可以在之后改变。
res <-
merge(ddply(DF, .(t), summarise, cnt=length(t)),
ddply(DF, .(t), colwise(Compose(unique, length))))
names(res)[-(1:2)] <- paste("cu", names(DF)[-1], sep="")
这给
> res
t cnt cux cuy
1 1 3 1 2
2 2 2 2 1
我没有downvote要么,但肯定这样想过,因为例如不能提供的输出相协调。 –
@Dwin:固定;对不起 – hoffmanc