Function | Input | Output | Best for |
apply | Rectangular | Rectangular or vector | Applying function to rows or columns |
lapply | Anything | List | Non-trivial operations on almost any data type |
sapply | Anything | Simplified (if possible) or list | Same as lapply, but with simplified output |
plyr::ddply | data.frame | data.frame | Applying function to groupings defined by variables |
Thursday, March 14, 2013
Apply-style commands in R
Here's a quick table of what I think are the most useful apply-style commands in R:
For alternatives to plyr, see this post on StackOverflow.
Labels:
apply,
by,
R,
split-apply-combine
Subscribe to:
Post Comments (Atom)
The one of this family I use most is tapply. If, say, you want a table of means of a numeric variable x arranged by groups in g, then tapply(x,g,mean) does the job.
ReplyDeleteI don't know about plyr, but tapply is easy enough for me.
Is there an easy way to do an apply command inputting multiple (indexable) objects? The function would then receive, for each ith invocation, the ith elements of each input object. The call might look something like multApply(listA, listB, listC, FUN=function(a_item, b_item, c_item){...}). This is a case where I still revert to a loop, but really don't need the loop counter for other purposes. One could re-package the data to use lapply (so that each element of a new list contained an item from A, B, and C), but thats a bit of a pain.
ReplyDeleteJust found mapply() which does just that. There are plyr versions too.
DeleteWhat a great idea for a post! Thanks for sharing I really enjoyed it.
ReplyDeleteBuy Pre Written Essays
Online Writing Services
Accounts Software For Small Business