Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 923
crf Avatar asked Jun 21 '12 02:06

crf


2 Answers

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)
like image 65
John Avatar answered Oct 19 '22 22:10

John


# 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
like image 30
Matt Parker Avatar answered Oct 19 '22 23:10

Matt Parker