I’d like to understand why the R is misreading the keys and E
When making a conditional structure with if
and else
, it is not necessary to put the logical test for the else
. This makes the test redundant. After all, if the condition of the if
is not satisfied, the only thing that can occur is its negation, by the principle of the excluded third.
Another detail to note is that z
has 100 elements. It is necessary to test whether each of them is in the range -1 to 1. To do this individually, the best thing to do is to build a for
, which is a loop of repetition. In the for
below, I will start my count at 1 and go to the last element of z
, denoted by length(z)
:
set.seed(1234) # comando para garantir que vamos gerar os mesmos valores com rnorm
for (j in 1:length(z)){
if(-1 >= z[j] | z[j] >= 1){
w <- w + 1
} else {
x <- x + 1
}
}
x
[1] 66
w
[1] 34
Now we have the desired result.
Another way to do this, which I consider more elegant, does not use the if
. See what happens when we run logic tests with a vector on R
:
a <- c(1, 2, 3, 4, 5)
a >= 4
[1] FALSE FALSE FALSE TRUE TRUE
He returns FALSE
or TRUE
for each position of the original vector. Internally, the R
treats FALSE
as the value 0
and TRUE
as a value 1
. So if I add up the amount of TRUE
of a vector, I can know how many of its positions satisfy the rule that interests me. In the above case, just do
sum(a >= 4)
[1] 2
and we have the desired result. For your example, with the vector z
, just do something like
sum(!(z < -1 | z > 1))
[1] 66
sum(z < -1 | z > 1)
[1] 34
and the same result is obtained. Note that !
is the command of R
to find the negation (or complement) of (z < -1 | z > 1)
.