## 4.4 Subsetting and assignment

All subsetting operators can be combined with assignment to modify selected values of an input vector: this is called subassignment. The basic form is x[i] <- value:

x <- 1:5
x[c(1, 2)] <- c(101, 102)
x
#> [1] 101 102   3   4   5

I recommend that you should make sure that length(value) is the same as length(x[i]), and that i is unique. This is because, while R will recycle if needed, those rules are complex (particularly if i contains missing or duplicated values) and may cause problems.

With lists, you can use x[[i]] <- NULL to remove a component. To add a literal NULL, use x[i] <- list(NULL):

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

Subsetting with nothing can be useful with assignment because it preserves the structure of the original object. Compare the following two expressions. In the first, mtcars remains a data frame because you are only changing the contents of mtcars, not mtcars itself. In the second, mtcars becomes a list because you are changing the object it is bound to.

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

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