Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

making sense of a for loop with an if statement in R

$
0
0

This is a practice question to prep for an exam. We are given this code:

x=c(T,T,F,T,F)

for (i in 1:5){
  if(i > 1 & i < 5){
     x[i ] = x[i-1] & x[i+1] & x[i]

     print(x)
  }
}

and asked to predict the output. The output is:

[1]  TRUE FALSE FALSE  TRUE FALSE
[1]  TRUE FALSE FALSE  TRUE FALSE
[1]  TRUE FALSE FALSE FALSE FALSE

and I cannot for the life of me make sense of this. Can someone please explain the logic behind the output? I have used for loops and if...else statements in other contexts but the true/false is really throwing me off. I'm assuming there are three lines out output because there are 3 values of i in the if statement. When I try to "run" the code in my head I come up with a single line of output, "TRUE, FALSE, FALSE, FALSE, FALSE", because i=1 and i=5 would be unchanged, and i=2,3,4 are false because x[i-1]&x[i+1]&x[i] give false as an answer under boolean logic.


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>