问题
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