我試圖通過使用 if 陳述句來檢查for 回圈中向量差異的每個分量的絕對值是否大于 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")
}
}
uj5u.com熱心網友回復:
你需要的是使用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")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342483.html
