用提取物子集矢量

时间:2016-02-05 16:39:33

标签: r magrittr

想象一下,我有矢量,我想删除一个特定的元素。我可以做以下

library(magrittr)

foo <- LETTERS[1:10]

foo %>% 
{
   bar <- .

   bar %>% 
     extract(bar %>% 
              equals("A") %>% 
              not)
}


[1] "B" "C" "D" "E" "F" "G" "H" "I" "J"

但如果我想更简洁一点,那就:

foo %>% 
  extract(. %>% 
            equals("A") %>% 
            not)

不起作用:

Error in extract(., . %>% equals("A") %>% not) : 
  invalid subscript type 'closure'

是不是还有更多的惯用magrittr'方法呢?

1 个答案:

答案 0 :(得分:1)

一种选择是将foo传递到子集化函数[,使用!=限制不等于A的元素:

foo %>% "["(. != "A")
# [1] "B" "C" "D" "E" "F" "G" "H" "I" "J"

magrittr包的别名[extract,因此相当于:

foo %>% extract(. != "A")
# [1] "B" "C" "D" "E" "F" "G" "H" "I" "J"