在R中,如何对多列进行无“by”分组的表格聚合?

6

我有一个包含x和y坐标点的2列数据框。我想生成一个每个点出现次数的表格。使用table()命令会产生所有可能的x-y对的表格。我可以通过以下方法消除多余的内容:

fullTable <- table(coords)
smalLTable <- subset(fullTable, fullTable > 0)

然后我确定我可以通过dimnames(fullTable)做一些处理来获取合适的坐标,但是有更好的方法吗?内置的方法?或者使用

coords <- data.frame(x = c(1, 1, 2, 2, 3, 3), y = c(1, 1, 2, 1, 1, 1))

将返回

x y count
1 1 2
2 1 1
2 2 1
3 1 2
5个回答

9

只使用原生的R语言,您可以做到:

aggregate(rep(1, nrow(coords)), by = list(x = coords$x, y = coords$y), sum)

1
coords 是一个数据框(已经是列表),因此稍微简短的解决方案是:aggregate(coords$x, by=coords, length) - Joshua Ulrich

8
比ddply更好的是count:
library(plyr)
count(coords)

相较于稀疏二维表格,它的速度更快。


4
您可以使用plyr库中的ddply函数来实现。
plyr::ddply(coords, .(x, y), summarize, count = length(x))

4

您还可以使用data.table

library(data.table)
DT <- data.table(coords)
DT[,.N,by=list(x,y)]
##   x y N
## 1: 1 1 2
## 2: 2 2 1
## 3: 2 1 1
## 4: 3 1 2

有关使用.N和使用data.table创建频率表的更多详细信息,请参见此答案


1
使用 dplyr
library(dplyr)
count(coords, x, y)

使用 data.table
library(data.table)
setDT(coords)
coords[, .(n = .N), by = .(x, y)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接