lobshi
February 27, 2019, 6:50am
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!
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)
lobshi
February 27, 2019, 10:21pm
4
Thank you so much for the explanation.
cderv
February 27, 2019, 10:46pm
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:
If your question has been answered, don't forget to mark the solution!
How do I mark a solution?
Find the reply you want to mark as the solution and look for the row of small gray icons at the bottom of that reply. Click the one that looks like a box with a checkmark in it:
[image]
Hovering over the mark solution button shows the label, "Select if this reply solves the problem". If you don't see the mark solution button, try clicking the three dots button ( ••• ) to expand the full set of options.
When a solution is chosen, the icon turns green and the hover label changes to: "Unselect if this reply no longer solves the problem". Success!
[solution_reply_author]
…
system
Closed
March 6, 2019, 10:47pm
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.