计算向量中的对数

Counting the number of pairs in a vector

假设我有以下向量:

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

我想知道以下类别中不同对的数量:

(1,1)、(-1,1)、(1,-1) 和 (-1,-1)

在我的示例中,每个正好有 1 对。

我一直在尝试用函数splitsetkey来解决这个问题,但是我无法进行分类

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 

这里有一个更好的替代方案,它也使用 split,遵循 @MartinMorgan 的回答模式:

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

或者

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

创建一个索引,该索引将重新循环到 select 第一个(或否定第二个)元素

> idx = c(TRUE, FALSE)

然后交叉制表观察结果

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