矩阵看起来像...

      [,1]   [,2]   [,3]   [,4]   [,5]
 [1,] "notB" "notB" "B"    "notB" "notB"
 [2,] "notB" "notB" "notB" "notB" "notB"
 [3,] "notB" "notB" "notB" "notB" "notB"
 [4,] "B"    "notB" "notB" "notB" "B"
 [5,] "notB" "notB" "notB" "notB" "notB"
 [6,] "notB" "B"    "B"    "notB" "B"
 [7,] "notB" "notB" "notB" "B"    "notB"
 [8,] "B"    "B"    "B"    "B"    "B"
 [9,] "B"    "B"    "notB" "B"    "notB"


想法是计数(在成千上万列的设置中),无论在哪个位置(例如, B B B notB notB notB notB notB notBnotB notB B B B notB notB notB notB

在上面发布的矩阵中,只有列[,4]满足B被“在一起”的条件。



这是生成矩阵的代码:

b=c(rep("B", 3), rep("notB", 6))
n = 1000
d = replicate(n,sample(b, replace=F))

最佳答案

另一种方法:

apply(mat,2, function(c) all(diff(which(c=="B")) == 1))


在这里,我们为每列提供一个apply函数,该函数检查alldiff对应的元素的索引之间的"B"区间是否为1。当且仅当所有"B"在一起时,此条件成立。

使用您发布的数据,您可以:

##   V1    V2    V3    V4    V5
##FALSE FALSE FALSE  TRUE FALSE


然后,我们可以使用which提取其为真的列:

which(apply(mat,2, function(c) all(diff(which(c=="B")) == 1)))
## V4
##  4


或者,正如@IaroslavDomin所说,我们可以改为apply该函数

apply(mat, 2, function(c){w <- which(c == "B"); length(w) == diff(range(w)) + 1})


这具有我们不必检查以确保"B"的相邻索引的所有差异都是1的优雅。相反,我们只需要检查最后一个和第一个之间的差异(即diff(range(w))加1)是否与该列中"B"的数量匹配。

数据:

mat <- structure(c("notB", "notB", "notB", "B", "notB", "notB", "notB",
"B", "B", "notB", "notB", "notB", "notB", "notB", "B", "notB",
"B", "B", "B", "notB", "notB", "notB", "notB", "B", "notB", "B",
"notB", "notB", "notB", "notB", "notB", "notB", "notB", "B",
"B", "B", "notB", "notB", "notB", "B", "notB", "B", "notB", "B",
"notB"), .Dim = c(9L, 5L), .Dimnames = list(NULL, c("V1", "V2",
"V3", "V4", "V5")))
      V1     V2     V3     V4     V5
 [1,] "notB" "notB" "B"    "notB" "notB"
 [2,] "notB" "notB" "notB" "notB" "notB"
 [3,] "notB" "notB" "notB" "notB" "notB"
 [4,] "B"    "notB" "notB" "notB" "B"
 [5,] "notB" "notB" "notB" "notB" "notB"
 [6,] "notB" "B"    "B"    "notB" "B"
 [7,] "notB" "notB" "notB" "B"    "notB"
 [8,] "B"    "B"    "B"    "B"    "B"
 [9,] "B"    "B"    "notB" "B"    "notB"

关于r - 如何检查矩阵的列是否遵循R中的预定顺序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41104650/

10-12 18:00