You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Many years ago, I was introduced to R by Cam Webb . At the time, his website contained a list of common data manipulations (original here). This list dated from Cam's early experience with R, and contained the R-help mailing list responses to a series of data manipulations. For a long time, I kept this file as a handy reference. I printed it out. I recommended it to friends.
Now I have been using R for years, and the state of the art has advanced considerably. Particulary, Hadley Wickham'sreshape2 and dplyr packages have transformed the way most useRs manipulate their data. I decided that it would be interesting to revisit my favourite resource and try my hand at solving these problems with tools from these two packages.
Many original responders suggested the use of table, referring to the original dataset:
C_alt<-with(A,table(c1,c2))
kable(C_alt)
id
a
b
c
d
A
3
2
0
0
B
0
0
1
1
although that solution is not "tidy" in the Hadlian sense -- i.e., it does not return a data.frame, but rather a table object. You can obtain a data.frame with dcast directly:
E<-data.frame(c1=c("A","B","C"), c2=1:3)
FF <- data.frame(c1=c("A","B","B","B","C","A"), c3=c("a","a","a","b","c","b"))
G <- left_join(FF, E)
## Joining by: "c1"
kable(G)
c1
c3
c2
A
a
1
B
a
2
B
a
2
B
b
2
C
c
3
A
b
1
the dplyr package supplies left_join(), which preserves the sequence of rows in its left argument. Alternative, as was originally suggested, one could use merge() :
To my surprise, each of these was actually a single line. The only exception was the first (GROUP), and that was because there are really two separate steps here -- the first to actually group the data, the second to apply summary functions to the data. dplyr automates both tasks, and supplies great readability.
@daattali to my dismay, I don't think I actually saved the source :( I might have even written this directly in markdown (in my naiveté). A version that includes tidyr is VERY NECESSARY, however! that's an awesome idea. In fact this thing is so old I think it actually predates tidyr, or at least my use of it!
@adletaw here is my take on your problem. It takes advantage of
ldply
's handy ability to turn list names into a column:Or an even simpler way: