marsilt
marsilt

Reputation: 27

Count certain number pairs that occurs in vector

Is there any good solution how to count certain number pairs in vector or column of data frame?

I have data like this and I´d like to count that how many pairs with combination 2 3 (or some other combination) occurs in vector. Or how many times 2 appears before 3.

 set.seed(1)
 sample(1:5, 50, replace=T)

And result should be:

number combination   count
2 3                  2
4 1                  4
5 4                  3

I tried function match but it didn´t work in combination of two numbers.

Any help would be appreciated,
Martin

Upvotes: 0

Views: 641

Answers (2)

droopy
droopy

Reputation: 2818

you can try something like this:

x <- sample(1:50, 50, rep=T)
table(paste(x[-length(x)], x[-1]))
# with dplyr
y <- data.frame(x=paste(x[-length(x)], x[-1]))
summarise(group_by(y,x), N=n())
# or if you need to keep the first and second value
x <- sample(1:5, 50, rep=T)
y <- data.frame(x1=x[-length(x)], x2=x[-1])
summarise(group_by(y, x1, x2), N=n())

Upvotes: 3

bartektartanus
bartektartanus

Reputation: 16080

Use table:

set.seed(1)
sample(1:5, 50, replace=T)
## [1] 2 2 3 5 2 5 5 4 4 1 2 1 4 2 4 3 4 5 2 4 5 2 4 1 2 2 1 2 5 2 3 3 3 1 5 4 4 1 4 3 5 4 4 3 3 4 1 3 4 4
table(data.frame(first=x[-length(x)],second=x[-1]))
##      second
## first 1 2 3 4 5
##     1 2 0 2 4 1
##     2 1 3 2 1 1
##     3 4 1 5 2 3
##     4 2 4 2 1 2
##     5 0 0 4 2 0

So the 5 5 pairs was 0, 3 1 was 4 and 3 3 was 5.

Upvotes: 1

Related Questions