'In R, how can I filter out specific values in an array using dplyr's piping operator (%>%)?
How can I use the dplyr/magrittr piping operator (%>%) to filter/subset an input array and remove a specific value from that input array?
In more concrete terms, suppose I have the following array:
y = c('a','x','a','b','x','b','c','x','c')
Let's say I want to remove all the occurrences of the 'x' item and get an array that looks like this: ('a','a','b','b','c','c'). How can I use the piping operator to do so?
Here is what I've tried so far and their respective results:
result = y %>%
filter(.!='x')
# This yields an error:
# Error in UseMethod("filter") :
# no applicable method for 'filter' applied to an object of class "character"
result = y %>%
{filter(., .!='x')}
# This also yields an error:
# Error in UseMethod("filter") :
# no applicable method for 'filter' applied to an object of class "character"
result = y %>%
`[` %>% {.!='x'}
print(result)
# [1] TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE TRUE
# This doesn't throw an error, but it also doesn't work. It just gives me the
# TRUE/FALSE array that represents which items to keep or discard.
It seems like the filter function doesn't work for this, and I'm not sure what else does.
So, back to my main point: how can I use the piping operator (%>%) to subset/filter an array and remove certain unwanted values?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
