In R, little things always bother me.
Say I have a data frame like this:
location species 1 seattle A 2 buffalo C 3 seattle D 4 newark J 5 boston Q
I would like to add a column to this frame that shows the number of times a location appears in the dataset, with a result similar to this:
location species freq-loc 1 seattle A 2
I know that using table(data$location) can give me a contingency table. But I donโt know how to match each value in the table with the corresponding record in the data frame. Can anyone help?
Update
Thank you so much for your help! Just for fun, I did a quiz to see how merge, plyr and ave solutions work compared to each other. The test suite is 10,000 rows of a subset of my original dataset of size 10 by ~ 7 mil .:
Unit: milliseconds expr min lq median uq max neval MERGE 110.877337 111.989406 112.585420 113.51679 120.23588 100 PLYR 26.305645 27.080403 27.576580 27.87157 68.40763 100 AVE 2.994528 3.117255 3.179898 3.35834 10.02955 100
source share