Subsetting vectors with extract

筅森魡賤 提交于 2019-12-13 01:13:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!