Logic And Programming

# logical comparisons

You already know that == means "equals," but did you know that != means "not equal?"

``````> x <- seq(0, 15, by = 3)
> x
  0  3  6  9 12 15
> x[x == 3]
 3
> x[x != 3]
  0  6  9 12 15```
```

Another useful, but rarely documented comparison is %in%, which is a logical comparison for whether the items in the object on the left are found in the object on the right:

``````> z <- c(10:20)
> x
  0  3  6  9 12 15
> z
 10 11 12 13 14 15 16 17 18 19 20
> x %in% z
 FALSE FALSE FALSE FALSE  TRUE  TRUE
> x[x %in% z]
 12 15```
```

# for loops

To cycle through a bit of code over and over, we can use a for() loop. In this (admittedly trivial) example, each value of y depends on the y-value before it:

``````> y <- numeric(10)
> y <- 4
> for(i in 2:10) { y[i] <- y[i-1] + 3 }
> y
  4  7 10 13 16 19 22 25 28 31```
```

A more intuitive for loop? I've been trying to model population growth over time using a simple leslie matrix format. For some reason, this was difficult for me to do with a for() loop, but I found the while() loop to be much more intuitive. I'm not sure what the differences are between them, but I guess while loops work more like for loops do in other programming languages. Here is a simplified version of what I did. mat is the leslie matrix, pop is the initial population vector. cbind() is also this nifty thing that concatenates the matrices. So if you have trouble with the for loop (like me), maybe you could try the while loop.

``````>mat<-matrix(c(0, 1.8, 1.8, 1.8, 1.8, 1.8, 1.8, 0, 0.4,
0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0.67, 0,
0, 0, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0.4, 0, 0,
0, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0,0,0.1,0),ncol=8,nrow=8,byrow=TRUE)
>pop<-matrix(c(75,50,30,25,25,15,15,15))
>i<-1
>while(i<=10){