Counting the number of pairs in a vector

[亡魂溺海] 提交于 2019-12-10 16:05:03

问题


Suppose that 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 1 pair of each.

I have been trying to solve this problem with the function split and setkey, but I can't do the categorization.


回答1:


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 a better alternative that also uses split, following the pattern of @MartinMorgan's answer:

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



回答2:


Create an index that will re-cycle to select the first (or when negated second) element

> idx = c(TRUE, FALSE)

Then cross-tabulate the occurrence of observations

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



回答3:


Or

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


来源:https://stackoverflow.com/questions/30489952/counting-the-number-of-pairs-in-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!