In R, a vector (a
in your question) can be subset with a logical index vector (b
in your question). If the corresponding members are TRUE
in the logical vector, the elements (of a
) are retained.
a = c (3, 4, 7, 8)
b = c(TRUE, TRUE, FALSE, FALSE)
a[b]
#[1] 3 4
a[b]
will retain only the first two elements of a
because only those values are TRUE
in b
. When you sum
3
and 4
, it is 7
If you give the “[” function a vector which is shorter than the vector being subset, you may get results that are surprising (and no warnings will appear):
a[ b[1:3] ]
[1] 3 4 8 # the fourth item in `a` appears because the logical vector is "recycled"
2
solved a is a numerical vector and b is logical. what is suma[b] [closed]