title | author | date | output | ||||
---|---|---|---|---|---|---|---|
Chapter 5 |
Julin Maloof |
2022-10-01 |
|
if
is really flow control. ifelse
is vectorized
2. In the following code, what will the value of y be if x is TRUE? What if x is FALSE? What if x is NA?
y <- if (x) 3
_TRUE: 3 _
_FALSE: NULL _
NA: NA # Wrong, code throws an error
no idea...
ifelse(TRUE, 1, "no")
## [1] 1
ifelse(FALSE, 1, "no")
## [1] "no"
ifelse(NA, 1, "no")
## [1] NA
numeric, character, logical
Read the documentation and write down the rules in your own words.
the output vector starts off is logical and then is coerced based on what comes in from yes and then from no. In the last example, since no values are taken from yes or no, it stays logical
Why does the following code work?
x <- 1:10
if (length(x)) "not empty" else "empty"
## [1] "not empty"
#> [1] "not empty"
x <- numeric()
if (length(x)) "not empty" else "empty"
## [1] "empty"
#> [1] "empty"
Because 0 is FALSE and anything >0 is TRUE
length(1:10)
## [1] 10
length(numeric())
## [1] 0
x <- numeric()
out <- vector("list", length(x))
for (i in 1:length(x)) {
out[i] <- x[i] ^ 2
}
out
## [[1]]
## [1] NA
not really sure
xs <- c(1, 2, 3)
for (x in xs) {
xs <- c(xs, x * 2)
}
xs
## [1] 1 2 3 2 4 6
The vector being iterated is not updated until after the for loop completes
for (i in 1:3) {
i <- i * 2
print(i)
}
## [1] 2
## [1] 4
## [1] 6
the index is updated at the beginning of each iteration