Could someone please point to how we can apply multiple functions to the same column using tapply (or any other method, plyr, etc) so that the result can be obtained in distinct columns). For eg., if I have a dataframe with
User MoneySpent
Joe 20
Ron 10
Joe 30
...
I want to get the result as sum of MoneySpent + number of Occurences.
I used a function like —
f <- function(x) c(sum(x), length(x))
tapply(df$MoneySpent, df$Uer, f)
But this does not split it into columns, gives something like say,
Joe Joe 100, 5 # The sum=100, number of occurrences = 5, but it gets juxtaposed
Thanks in advance,
Raj
You can certainly do stuff like this using
ddplyfrom theplyrpackage:You can keep listing more summary functions, beyond just two, if you like. Note I’m being a little tricky here in calling
NROWon an internal variable inddplycalledpiece. You could have just done something likelength(y)instead. (And probably should; referencing the internal variablepieceisn’t guaranteed to work in future versions, I think. Do as I say, not as I do and just uselength().)