问题
Imagine I have vector, and I want to remove a specific element. I could do the following
library(magrittr)
foo <- LETTERS[1:10]
foo %>%
{
bar <- .
bar %>%
extract(bar %>%
equals("A") %>%
not)
}
[1] "B" "C" "D" "E" "F" "G" "H" "I" "J"
But if I'd like to be more succinct, this:
foo %>%
extract(. %>%
equals("A") %>%
not)
doesn't work:
Error in extract(., . %>% equals("A") %>% not) :
invalid subscript type 'closure'
Isn't there are more idiomatically magrittr
'y way to do this?
回答1:
One option would be to pipe foo
into the subsetting function [
, limiting to elements that do not equal A using !=
:
foo %>% "["(. != "A")
# [1] "B" "C" "D" "E" "F" "G" "H" "I" "J"
The magrittr
package has aliased [
as extract
, so this is equivalent to:
foo %>% extract(. != "A")
# [1] "B" "C" "D" "E" "F" "G" "H" "I" "J"
来源:https://stackoverflow.com/questions/35229178/subsetting-vectors-with-extract