【问题标题】:The logical comparison inside the loop crashes when it encounters zero循环内部的逻辑比较在遇到零时崩溃
【发布时间】:2021-12-29 12:49:17
【问题描述】:

我想用代码解释我的问题

example_1 <- sample(-100:100, 100)    # simple sample for my question
example_1[30] <- NA                   # changed one of them to NA
not_equal_zero <- matrix(NA, 100, 1)  # matrix to find out if there is any zeros (1 for TRUE, 0 for FALSE)

for (i in 1:100) {                    # check each observation if it is 0 assign 1 to "not equal zero matrix"
  if (example_1[i] == 0) {
    not_equal_zero[i] <- 1
  } else {
    not_equal_zero[i] <- 0
  }
}

当 i = 30 时,它找到 0,然后终止。我不是只检查零。我有特殊的价值观。这个问题有什么解决办法?

2 == 0    # it gives FALSE
0 == 0    # it gives TRUE
NA == 0   # it gives NA but i need FALSE

【问题讨论】:

    标签: r loops logical-operators


    【解决方案1】:

    NAanything 相比给出 NA。您可能想要替换:

    if (example_1[i] == 0)
    

    与:

    if (!is.na(example_1[i]) && example_1[i] == 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 2010-11-08
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      相关资源
      最近更新 更多