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
ch_27_solutions
Prerequisites:
27.2.4 Exercises:
All 3 parts below:
<- function(vector) { even_position seq(2, length(vector), 2)] vector[ }
<- function(vector) { cut_last_element -length(vector)] vector[ }
<- function(vector) { even_position_no_missing %% 2 == 0 & !is.na(vector))] vector[(vector }
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 thewhich
function is able to return NaN.<- c(10, NA, NaN) vector_x
-which(vector_x > 0)] vector_x[## [1] NA NaN <= 0] vector_x[vector_x ## [1] NA NA
27.3.4 Exercises:
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.
<- c(n1 = 'red', n2 = 'blue', n3 = 'green', n4= 'yellow') vector_y 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
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).
<- list( pepper_1 packet = list(1,2) ) <- list( pepper_2 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