rreplace

Why replace works with a boolean mask?


The R documentation for replace states:

replace replaces the values in x with indices given in list by those given in values. If necessary, the values in values are recycled.

Usage

replace(x, list, values)

Arguments

x a vector.

list an index vector.

values replacement 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?


Solution

  • 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:

    1. 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.