How can I make a list of all the unique pairs of data points in R?

So, I have two data point vectors, and I would like to make a list of each unique pair along with this pair frequency. I know that I can use a table for this with one of the vectors, but I cannot figure out how to do this with pairs.

+5
source share
3 answers

simply...

dat <- data.frame(x = sample(letters[1:3], size = 100, replace = TRUE),
    y = sample(letters[1:3], size = 100, replace = TRUE) )

unique(dat)
table(dat)

or, say, your vectors are just x and y, and you only need a table ...

table(x,y)
+8
source
# A sample dataset:
dat <- data.frame(x = sample(letters, size = 1000, replace = TRUE),
                  y = sample(letters, size = 1000, replace = TRUE)
)

# Aggregating using just base R:
as.data.frame(table(dat$x, dat$y))

# With plyr
library(plyr)
count(dat, vars = c(x, y))
count(dat) # Or, less generalizably
+2
source

If vec1and vec2are the considered vectors:

points <- mapply(c, vec1, vec2, SIMPLIFY=FALSE)
uniq.points <- unique(points)
freqs <- sapply(uniq.points, FUN=function(point) length(which(points %in% list(point))))
cbind(do.call(rbind, uniq.points), freqs)  # matrix of points and freqs
0
source

All Articles