ch_27_solutions

Prerequisites:

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.4     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

27.2.4 Exercises:

  1. All 3 parts below:

    even_position <- function(vector) {
      vector[seq(2, length(vector), 2)]
    }
    cut_last_element <- function(vector) {
      vector[-length(vector)]
    }
    even_position_no_missing <- function(vector) {
      vector[(vector %% 2 == 0 & !is.na(vector))]
    }
  2. the which function only checks if true and does not coerce the vector to logical. This matters because the base R solution coerces NaN to the logical NA but the which function is able to return NaN.

    vector_x <- c(10, NA, NaN)
    vector_x[-which(vector_x > 0)]
    ## [1]  NA NaN
    vector_x[vector_x <= 0]
    ## [1] NA NA

27.3.4 Exercises:

  1. Subsetting with [[ with a positive integer out of bounds returns an error. Similarly, subsetting with [[ on a name that doesn’t exist also returns an error. This is sensible because you are trying to extract a component of a vector which doesn’t exist.

    • Can see in the example below that before drilling down into the component, the single bracket for names and integers out of range returns a sublist without a name, so consequently the double brackets have nothing to extract.
    vector_y <- c(n1 = 'red', n2 = 'blue', n3 = 'green', n4= 'yellow')
    
    str(vector_y[4])
    ##  Named chr "yellow"
    ##  - attr(*, "names")= chr "n4"
    str(vector_y[5])
    ##  Named chr NA
    ##  - attr(*, "names")= chr NA
    
    str(vector_y['n4'])
    ##  Named chr "yellow"
    ##  - attr(*, "names")= chr "n4"
    str(vector_y['n5'])
    ##  Named chr NA
    ##  - attr(*, "names")= chr NA
  2. It depends on the type of the “pepper packet”.

    • If the packet is a list, than [ returns a list and [[ returns the component of the list.

    • If the packet is a vector, than [ returns the first element and [[ also returns the element (since there is no outer structure to a vector).

    pepper_1 <- list(
      packet = list(1,2)
    )
    
    pepper_2 <- list(
      packet = c(1,2)
    )
    
    str(pepper_1[[1]][1])
    ## List of 1
    ##  $ : num 1
    str(pepper_1[[1]][[1]])
    ##  num 1
    
    str(pepper_2[[1]][1])
    ##  num 1
    str(pepper_2[[1]][[1]])
    ##  num 1