我曾希望使用ddply的模式函数按时间段为某个用户查找最常见的字符串。
这与this问题和this question显著相关。
使用与此类似的数据集:
Data <- data.frame(
groupname = as.factor(sample(c("red", "green", "blue"), 100, replace = TRUE)),
timeblock = sample(1:10, 100, replace = TRUE),
someuser = sample(c("bob", "sally", "sue"), 100, replace = TRUE))我试过:
groupnameagg<- ddply(Data, .(timeblock, groupname, someuser), summarise, groupmode = mode(groupname))但这不是我所期望的。它返回:
> head(groupnameagg$groupname)
[1] "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" timeblock username mostcommongroupforuser
1 bob red
1 sally red
1 sue green
2 bob green
2 sally blue
2 sue red发布于 2013-06-23 21:33:48
认为聚合应该对两者都有好处。
第1部分
aggregate(Data$groupname,by=list(Data$timeblock,Data$someuser),
function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))] })第2部分
aggregate(Data$groupname,by=list(Data$timeblock,Data$someuser),
function(x) {
levels(Data$groupname)[max(as.numeric(x))] })发布于 2013-06-23 21:01:53
使用来自ddply的plyr
ddply(Data, .(timeblock, groupname, someuser),
function(x){as.character(
unique(
x$groupname[x$someuser==
names(which.max(table(x$someuser)))
]
)
)
}
)
timeblock groupname someuser V1
1 1 blue bob blue
2 1 blue sally blue
3 1 green bob green
.........https://stackoverflow.com/questions/17265141
复制相似问题