gpt4 book ai didi

R - 不使用循环遍历不同的矩阵!帮忙简单一个代码

转载 作者:行者123 更新时间:2023-12-02 15:15:44 27 4
gpt4 key购买 nike

所以我有两个独立的矩阵(mat1 和 mat2)我需要仔细检查它们才能进行检查。我需要将结果存储到第三个矩阵中。

我觉得我的代码对于这个目的来说很长。

我想听听您的一些建议,以避免循环。

所以我的第一个矩阵看起来像这样(dput在最后)

  wit5.001 wit5.002 wit5.003 wit5.004 wit5.005 wit5.006 wit5.007 wit5.008 wit5.009 wit5.010
[1,] 1 1 1 1 1 1 1 1 1 1
[2,] 1 1 1 1 1 1 1 1 1 1
[3,] 1 1 1 1 1 1 1 1 1 1
[4,] 1 1 1 1 1 1 1 1 1 1
[5,] 1 1 1 1 1 1 1 0 1 1
[6,] 1 1 1 1 1 1 1 0 0 0
[7,] 0 1 1 1 1 1 1 1 1 1
[8,] 1 1 1 1 1 1 1 1 1 1
[9,] 1 1 1 1 1 1 1 1 1 1
[10,] 1 1 1 1 1 1 1 1 1 1

我的第二个矩阵具有类似的结构。

在这里,我创建了第三个矩阵 - 为了存储检查结果。

matCheck <- matrix('ok', ncol = ncol(mat1), nrow = nrow(mat1))

这是我的循环 - 我想避免它

for(j in 1:ncol(mat1)){
for(i in 1:nrow(mat1)){

if(mat1[i,j] == 1 & mat2[i,j] == 1)
{matCheck[i,j] <- 'ok'}

if(mat1[i,j] != 1 & mat2[i,j] == 1)
{matCheck[i,j] <- '!'}

}
}

检查结果

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
[2,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
[3,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
[4,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
[5,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
[6,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "!" "!" "ok"
[7,] "!" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
[8,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
[9,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
[10,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"

有什么建议吗?

这是矩阵 1

mat1 = structure(c(1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1), .Dim = c(10L,
10L), .Dimnames = list(NULL, c("wit5.001", "wit5.002", "wit5.003",
"wit5.004", "wit5.005", "wit5.006", "wit5.007", "wit5.008", "wit5.009",
"wit5.010")))

这是矩阵 2

mat2 = structure(c(1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 
1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0,
0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), .Dim = c(10L,
10L), .Dimnames = list(NULL, c("wit5.020", "wit5.021", "wit5.022",
"wit5.023", "wit5.024", "wit5.025", "wit5.026", "wit5.027", "wit5.028",
"wit5.029")))

最佳答案

对于给出的示例,结果可以构造为

matCheck <- ( mat1 | !mat2 )

这相当于将 matCheck 初始化为 true,然后在 !mat1 & mat2 中填充 false(如在 OP 的循环中)。括号是可选的,但它更容易阅读(我认为)。

关于R - 不使用循环遍历不同的矩阵!帮忙简单一个代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30942574/

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