dplyr filter on a vector rather than a dataframe in R

后端 未结 3 639
傲寒
傲寒 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.

    0 讨论(0)
  • 2021-02-08 15:22

    Pretty sure dplyr only really operates on data.frames. Here's a two line example coercing the vector to a data.frame and back.

    myDf = data.frame(states = gsub(" ", "-", tolower(state.name))) %>% filter(states != "alaska")
    all_states = myDf$states
    

    or a gross one liner:

    all_states = (data.frame(states = gsub(" ", "-", tolower(state.name))) %>% filter(states != "alaska"))$states
    
    0 讨论(0)
  • 2021-02-08 15:24

    You may like to try magrittr::extract. e.g.

    > library(magrittr)
    
    > c("A", "B", "C", "D") %>% extract(.!="A")
    [1] "B" "C" "D"
    

    For more extract-like functions load magrittr package and type ?alises.

    0 讨论(0)
提交回复
热议问题