在 R 中,总是让我感到困惑的小事情。
假设我有一个这样的数据框:
location species
1 seattle A
2 buffalo C
3 seattle D
4 newark J
5 boston Q
我想在此框架中附加一列,显示某个位置在数据集中出现的次数,结果如下:
location species freq-loc
1 seattle A 2 #there are 2 entries with location=seattle
2 buffalo C 1 #there is 1 entry with location=buffalo
3 seattle D 2
4 newark J 1
5 boston Q 1
我知道使用
table(data$location)
可以给我一张列联表。但我不知道如何将表中的每个值映射到数据框中的相应条目。有人可以帮忙吗?更新
非常感谢大家的帮助!出于兴趣,我运行了一个基准测试,以查看合并、plyr 和 ave 解决方案如何相互比较。测试集是我原始 10 x 7mil 数据集的 10,000 行子集。:
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
最佳答案
这是 ave
的基本 R 方式.
transform(d, freq.loc = ave(seq(nrow(d)), location, FUN=length))
关于r - 将列添加到显示变量频率的数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17030204/