Skip to content

Latest commit

 

History

History
170 lines (114 loc) · 2.17 KB

Chapter_5.md

File metadata and controls

170 lines (114 loc) · 2.17 KB
title author date output
Chapter 5
Julin Maloof
2022-10-01
html_document
keep_md
true

Chapter 5 Flow Control

Quiz

1. What is the difference between if and ifelse()?

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

3. What does switch("x", x = , y = 2, z = 3) return?

no idea...

5.2.4 Exercises

1. What type of vector does each of the following calls to ifelse() return?

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

Exercises 5.3.3

1. Why does this code succeed without errors or warnings?

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

2. When the following code is evaluated, what can you say about the vector being iterated?

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

3. What does the following code tell you about when the index is updated?

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