[英]Aggregating table() over multiple columns in R without a “by” breakdown
我有一個點的x坐標和y坐標的2列數據框。 我想生成一個表,列出每個點的出現次數。 使用table()
命令會為所有可能的xy對生成一張表。 我可以用消除多余的東西
fullTable <- table(coords)
smalLTable <- subset(fullTable, fullTable > 0)
然后,我確定我可以使用dimnames(fullTable)
進行一些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
僅使用Vanilla R,您就可以
aggregate(rep(1, nrow(coords)), by = list(x = coords$x, y = coords$y), sum)
優於ddply是count
:
library(plyr)
count(coords)
對於稀疏的2d結果,它也比表格快得多。
您也可以使用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
您可以從plyr
庫中使用ddply
plyr::ddply(coords, .(x, y), summarize, count = length(x))
與dplyr
library(dplyr)
count(coords, x, y)
帶有data.table
library(data.table)
setDT(coords)
coords[, .(n = .N), by = .(x, y)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.