简体   繁体   中英

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

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

it's just...

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 want the table...

table(x,y)
# 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

If vec1 and vec2 are the vectors in question:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM