在 for 循环内的 if 语句内选择向量的组件

Selecting the components of a vector inside an if statement inside a for loop

我正在尝试使用 if 语句检查 for 循环内向量 differenza 的每个分量的绝对值是否大于 0.001,但似乎我我没有选择组件,因为出现错误:

Warning in if (abs(differenza[i]) > 0.001) { :
  the condition has length > 1 and only the first element will be used

我犯了什么错误?

lambda = 10
n = 10
p = lambda/n
K = 10
x = 0:K

denbinom = dbinom(x, n, p)
denpois = dpois(x, lambda)

differenza = denbinom - denpois

for (i in differenza) {
  if (abs(differenza[i]) > 0.001) {
    cat("Componente", i > 0.001, "\n")
  }
  if (abs(differenza[i]) <= 0.001) {
    cat("Componente", i, "ok")
  }
}

你需要的是使用seq_along():

for (i in seq_along(differenza)) {
  if (abs(differenza[i]) > 0.001) {
    cat("Componente", i > 0.001, "\n")
  }
  if (abs(differenza[i]) <= 0.001) {
    cat("Componente", i, "ok")
  }
}

您还可以简化您的 if 语句:

for (i in seq_along(differenza)) {
  if (abs(differenza[i]) > 0.001) {
    cat("Componente", TRUE, "\n")
  }else {
    cat("Componente", i, "ok", "\n")
  }
}

编辑

如果您想打印 i 的真实值:

for (i in seq_along(differenza)) {
  if (abs(differenza[i]) > 0.001) {
    cat("Componente", i,  "> 0.001", "\n")
  }
  if (abs(differenza[i]) <= 0.001) {
    cat("Componente", i, "ok", "\n")
  }
}