Yaahtzeck
Yaahtzeck

Reputation: 227

Counting unique pairs of data R

I have a following data set

data1 = data.frame("Element" = sample(c(1:100), 600, replace = T))
data1$Factor2 = sample(c("E", "F", "G"), 600, replace = T)

I'd like to count the number of Elemens that got matched with each factor from Factor2. For example, an output could like like the following table:

Factor Number of elements

E     45
F     67
G     34

which would mean there are 45 distinct rows such as: E,1;E11;E:20. Although row E,1 appears more times, I am not interested in how many times each combination appears, I am interested in how many unique combinations there were.

Upvotes: 0

Views: 646

Answers (2)

akrun
akrun

Reputation: 886948

An option with dplyr

library(dplyr)
data1 %>% 
    distinct() %>% 
    count(Factor2)

Upvotes: 1

G5W
G5W

Reputation: 37641

You can use unique to get the distinct rows and then just create a table of how many times each factor occurred. I am setting the seed to make the data reproducible.

set.seed(2018)
data1 = data.frame("Element" = sample(c(1:100), 600, replace = T))
data1$Factor2 = sample(c("E", "F", "G"), 600, replace = T)

table(unique(data1)$Factor2)
 E  F  G 
85 92 79 

Upvotes: 1

Related Questions