4.3 Subsetting and Assignment

  • Subsetting can be combined with assignment to edit values
x <- c("Tigers", "Royals", "White Sox", "Twins", "Indians")

x[5] <- "Guardians"

x
#> [1] "Tigers"    "Royals"    "White Sox" "Twins"     "Guardians"
  • length of the subset and assignment vector should be the same to avoid recycling

You can use NULL to remove a component

x <- list(a = 1, b = 2)
x[["b"]] <- NULL
str(x)
#> List of 1
#>  $ a: num 1

Subsetting with nothing can preserve structure of original object

# mtcars[] <- lapply(mtcars, as.integer)
# is.data.frame(mtcars)
# [1] TRUE
# mtcars <- lapply(mtcars, as.integer)
#> is.data.frame(mtcars)
# [1] FALSE