Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of consecutive pairs in a vector

Suppose that I have the following vector:

    V<-c(-1,-1,-1,-1,-1,-1,-1,-1,1,1) 

and I want to count the number of CONSECUTIVE pairs in the following categories:

    (1,1), (-1,1), (1,-1), and (-1,-1).

In my example, there are seven consecutive pairs of (-1,-1), one pair of (-1,1), and 1 pair of (1,1).

I am trying to solve this problem using the split function, but I have not been able to figure out the correct factors.

The idea is to pair the 1st observation with the 2nd. The 2nd with the 3rd and so on. The final pair should be the (n-1)th observation with the nth observation.

like image 876
ju.arroyom Avatar asked Nov 28 '22 10:11

ju.arroyom


2 Answers

All consecutive pairs can be represented by two parallel vectors, omitting the last or the first observation

x <- V[-length(V)]
y <- V[-1]

and then cross-tabulating these

> xtabs(~ x + y)
    y
x    -1 1
  -1  7 1
  1   0 1

or in slightly different form

> as.data.frame(xtabs(~x+y))
   x  y Freq
1 -1 -1    7
2  1 -1    0
3 -1  1    1
4  1  1    1
like image 180
Martin Morgan Avatar answered Dec 15 '22 09:12

Martin Morgan


Maybe something like that

library(zoo)
table(rollapply(V, 2, toString))
# -1, -1  -1, 1   1, 1 
#      7      1      1 

Or with base R

table(paste(head(V, -1), tail(V, -1)))
# -1 -1  -1 1   1 1 
#     7     1     1 

Or as per @akruns comment, without paste

table(head(V, -1), tail(V, -1))
#    -1 1
# -1  7 1
#  1  0 1

Or

as.data.frame(table(head(V, -1), tail(V, -1)))
#   Var1 Var2 Freq
# 1   -1   -1    7
# 2    1   -1    0
# 3   -1    1    1
# 4    1    1    1
like image 29
David Arenburg Avatar answered Dec 15 '22 08:12

David Arenburg