简体   繁体   English

如何列出R中所有唯一的数据点对?

[英]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... 或者,说你的向量只是x,而你只需要表...

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: 如果vec1vec2是有问题的向量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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