有人可以指出我们如何使用tapply(或任何其他方法,plyr等)将多个函数应用于同一列,以便可以在不同的列中获得结果.例如,如果我有一个数据帧
User MoneySpent
Joe 20
Ron 10
Joe 30
...
Run Code Online (Sandbox Code Playgroud)
我希望得到的结果是MoneySpent + Occurences数量的总和.
我使用了像 -
f <- function(x) c(sum(x), length(x))
tapply(df$MoneySpent, df$Uer, f)
Run Code Online (Sandbox Code Playgroud)
但这不会将其分成列,给出类似的说法,
Joe Joe 100, 5 # The sum=100, number of occurrences = 5, but it gets juxtaposed
Run Code Online (Sandbox Code Playgroud)
提前致谢,
拉吉
你当然可以使用ddply这个plyr包来做这样的事情:
dat <- data.frame(x = rep(letters[1:3],3),y = 1:9)
ddply(dat,.(x),summarise,total = NROW(piece), count = sum(y))
x total count
1 a 3 12
2 b 3 15
3 c 3 18
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以继续列出更多摘要功能,而不仅仅是两个.请注意,我呼吁是一个有点棘手,在这里NROW上的内部变量ddply叫piece.你可能刚刚做了类似的事情length(y).(并且可能应该; piece我认为,引用内部变量并不能保证在未来版本中有效.按照我的说法,不要像我一样,只是使用length().)
ddply()在概念上是最清晰的,但有时tapply为了速度原因而使用它是有用的,在这种情况下,以下工作:
do.call( rbind, tapply(df$MoneySpent, df$User, f) )
Run Code Online (Sandbox Code Playgroud)