I'm trying to check if the absolute value of each component of the vector differenza inside a for loop is greater than 0.001 by using if statements, but it seems that I'm not selecting a component because I got the error:
Warning in if (abs(differenza[i]) > 0.001) { :
the condition has length > 1 and only the first element will be used
Which kind of mistake did I make?
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")
}
}
CodePudding user response:
What you need is to use 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")
}
}
You can also simplify your if statement:
for (i in seq_along(differenza)) {
if (abs(differenza[i]) > 0.001) {
cat("Componente", TRUE, "\n")
}else {
cat("Componente", i, "ok", "\n")
}
}
Edit
If you wish to print the real values of 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")
}
}