dplyr filter on a vector rather than a dataframe in R

后端 未结 3 640
傲寒
傲寒 2021-02-08 14:57

This seems like a simple question, but I have not come across a clean solution for it yet. I have a vector in R and I want to remove certain elements from the vector, however I

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-08 15:16

    Sorry for posting on a 5-month-old question to archive a simpler solution.

    Package dplyr can filter character vectors in following ways:

    > c("A", "B", "C", "D") %>% .[matches("[^AB]", vars=.)]
    [1] "C" "D"
    > c("A", "B", "C", "D") %>% .[.!="A"]
    [1] "B" "C" "D"
    

    The first approach allows you to filter with regular expression, and the second approach uses fewer words. It works because package dplyr imports package magrittr albeit masks its functions like extract, but not the placeholder ..

    Details of placeholder . can be found on within help of forward-pipe operator %>%, and this placeholder has mainly three usage:

    • Using the dot for secondary purposes
    • Using lambda expressions with %>%
    • Using the dot-place holder as lhs

    Here we are taking advantage of its 3rd usage.

提交回复
热议问题