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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With