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
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.
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
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
.