Counting the number of pairs in vector

Suppose I have the following vector:

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

And I want to know the number of different pairs in the following categories:

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

In my example, there is exactly one pair of each.

I am trying to solve this problem with the function splitand setkey, but I can not categorize.

+4
source share
3 answers
ng <- length(V)/2
table(sapply(split(V,rep(1:ng,each=2)),paste0,collapse="&"))
# -1&-1  -1&1  1&-1   1&1 
#     1     1     1     1 

Here is the best alternative that also uses splitfollowing the @MartinMorgan answer pattern:

table(split(V,1:2))
#     2
# 1    -1 1
#   -1  1 1
#   1   1 1
+2
source

Create an index to be reprogrammed to select the first (or negative second) item

> idx = c(TRUE, FALSE)

Then cross-inherit the appearance of observations

> xtabs(~V[idx] + V[!idx])
      V[!idx]
V[idx] -1 1
    -1  1 1
    1   1 1
+2
source

table(apply(matrix(v, ncol = 2, byrow = TRUE), 1, paste, collapse = ",") )
+1

All Articles