gpt4 book ai didi

r - 如何检查矩阵的列是否遵循R中的预定顺序?

转载 作者:行者123 更新时间:2023-12-03 03:17:32 26 4
gpt4 key购买 nike

矩阵看起来像......

      [,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 B notB notB notB notB notB notB,或notB 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每列的一个函数,用于检查是否 all diff对应于 "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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com