Aggregate table () across multiple columns in R without column breakdown

I have a 2-column data frame of the x- and y-coordinates of the points. I want to create a table from the number of occurrences of each point. Using the command table(), a table is created for all possible xy pairs. I can exclude additional functions with

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

And then I'm sure I can do something with dimnames(fullTable)to get the appropriate coordinates, but is there a better way? Is something built? Something with

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

will return

x y count
1 1 2
2 1 1
2 2 1
3 1 2
+5
source share
5 answers

Using only Vanilla R, you can do

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

Better than ddply count:

library(plyr)
count(coords)

, 2d.

+7

You can use ddplyin the libraryplyr

plyr::ddply(coords, .(x, y), summarize, count = length(x))
+4
source

You can also use 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

For more information on usage, .Nsee this answer and create frequency tables withdata.table

+4
source

WITH dplyr

library(dplyr)
count(coords, x, y)

with data.table

library(data.table)
setDT(coords)
coords[, .(n = .N), by = .(x, y)]
+1
source

All Articles