7.2 For loops

Temp conversion functions

f_k <- function(f_temp) {
    ((f_temp - 32) * (5 / 9)) + 273.15
}


k_c <- function(temp_k) {
    if (is.na(temp_k)) {
        return(NA)
    } else if (temp_k < 0) {
        warning('you passed in a negative Kelvin number')
        # stop()
        return(NA)
    } else {
        temp_c <- temp_k - 273.15
        return(temp_c)
    }
}

f_c <- function(temp_f) {
    temp_k <- f_k(temp_f)
    temp_c <- k_c(temp_k)
    return(temp_c)
}
for (pizza in f_values) {
    print(pizza)
    converted <- f_c(pizza)
    print(converted)
}
## [1] 0
## [1] -17.77778
## [1] 32
## [1] 0
## [1] 212
## [1] 100
## [1] -40
## [1] -40
# 1:length(f_values)
# seq_along(f_values)
for (i in seq_along(f_values)) {
    print(i)
    val <- f_values[i]
    print(val)
    
    converted <- f_c(val)
    print(converted)
}
## [1] 1
## [1] 0
## [1] -17.77778
## [1] 2
## [1] 32
## [1] 0
## [1] 3
## [1] 212
## [1] 100
## [1] 4
## [1] -40
## [1] -40

7.2.1 Pre allocating in a loop

# prepopulate an empty vector
converted_values <- vector("double", length(f_values))
for (to_be_converted_position in seq_along(f_values)) {
    converted <- f_c(to_be_converted_position)
    converted_values[to_be_converted_position] <- converted
}
converted_values
## [1] -17.22222 -16.66667 -16.11111 -15.55556