The R documentation for replace states:
replacereplaces the values inxwith indices given inlistby those given invalues. If necessary, the values invaluesare recycled.
Usage
replace(x, list, values)
Arguments
xa vector.
listan index vector.
valuesreplacement values.
Using a numeric index vector works as expected:
replace(c(1,2,3,4), c(2, 4), 0)
# [1] 1 0 3 0
However, I don't understand why it seems to work also with a boolean (logical) mask:
replace(c(1,2,3,4), c(FALSE, TRUE, FALSE, TRUE), 0)
# [1] 1 0 3 0
Is this usage "official"? Is this undocumented? Did the R developers forgot to document this usage?
The list argument in replace is an index vector. From An Introduction to R; 2.7 Index vectors:
index vectors can be any of four distinct types.
...including:
- A logical vector
See also R Language Definition; 3.4.1 Indexing by vectors.
replace is implemented as
x[list] <- values
x
Thus, see ?"[<-", and the Usage x[i] <- value and its i argument:
For
[-indexing [...]i[...] can be logical vectors, indicating elements/slices to select.