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
:
1:5
x <-c(1, 2)] <- c(101, 102)
x[
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)
:
list(a = 1, b = 2)
x <-"b"]] <- NULL
x[[str(x)
#> List of 1
#> $ a: num 1
list(a = 1, b = 2)
y <-"b"] <- list(NULL)
y[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.
lapply(mtcars, as.integer)
mtcars[] <-is.data.frame(mtcars)
#> [1] TRUE
lapply(mtcars, as.integer)
mtcars <-is.data.frame(mtcars)
#> [1] FALSE