Apply multiple functions to column using tapply

后端 未结 2 1099
醉梦人生
醉梦人生 2020-12-09 22:56

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 dist

相关标签:
2条回答
  • 2020-12-09 23:27

    ddply() is conceptually the clearest, but sometimes it is useful to use tapply instead for speed reasons, in which case the following works:

    do.call( rbind, tapply(df$MoneySpent, df$User, f) )
    
    0 讨论(0)
  • 2020-12-09 23:36

    You can certainly do stuff like this using ddply from the plyr package:

    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
    

    You can keep listing more summary functions, beyond just two, if you like. Note I'm being a little tricky here in calling NROW on an internal variable in ddply called piece. You could have just done something like length(y) instead. (And probably should; referencing the internal variable piece isn't guaranteed to work in future versions, I think. Do as I say, not as I do and just use length().)

    0 讨论(0)
提交回复
热议问题