Subsetting a vector using a boolean vector with different length

Hi,
How can expect the output when I subset a vector using a vector of boolean values with different length. For example:

a <- c(1,2,3)
b <- c(TRUE,FALSE)
d <- c(FALSE,TRUE)
e <- c(TRUE)
f <- c(FALSE)
a[b]; a[c]; a[d]; a[e]; a[f]

Is there any rule for this situation?

Thanks!

The values get recycled from the start to match the length of a.

This can be useful, but can also lead to unexpected output.

Just to illustrate upon Martin's point:

a <- 1:5 # modified from c(1, 2, 3) to make the illustration easier

b <- c(TRUE, FALSE)
a[b] # behaves like a[c(TRUE, FALSE, TRUE, FALSE, TRUE)]
#> [1] 1 3 5

d <- c(FALSE, TRUE)
a[d] # behaves like a[c(FALSE, TRUE, FALSE, TRUE, FALSE)]
#> [1] 2 4

e <- c(TRUE)
a[e] # behaves like a[c(TRUE, TRUE, TRUE, TRUE, TRUE)]
#> [1] 1 2 3 4 5

f <- c(FALSE)
a[f] # behaves like a[c(FALSE, FALSE, FALSE, FALSE, FALSE)]
#> integer(0)

Created on 2019-02-27 by the reprex package (v0.2.1)

Thank you so much for the explanation.

If your question's been answered, would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.