Doubt with If statements in R

Asked

Viewed 48 times

3

In this code I am wanting to record the amount of values of z such that -1 < z < 1 inside x, and z < -1 or z > 1 in w. It rotates the rnorm(100)(that is, it creates 100 observations of a standard normal random variable) and records its numbers in the z, but only one number is recorded in w or x and then accuses error on LSE and keys. I would like to understand why the R be accusing error in the keys and in IS and what I did wrong, and if I can by writing something like if(-1<z<1) to make it easier.

# x = números de -1 a 1 // w = números maiores que 1 e menores que -1
x<-0
w<-0
z <- rnorm(100)
if(-1 >= z | z >= 1){
  w<-w + 1
} else{
  x <- x + 1
}

1 answer

3


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).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.