# Subsetting a vector using a boolean vector with different length

#1

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!

0 Likes

#2

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

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

0 Likes

#3

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)

0 Likes

#4

Thank you so much for the explanation.

0 Likes

#5

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:

0 Likes

closed #6

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.

0 Likes