When I try to filter a dataframe using the %in%
operator using a pull()
subfilter, It does not work.
However, When I store the pull()
subquery in a variable, and then use the %in%
operator on the variable, It does work.
I use as an example the well known mtcars dataset.
library(tidyverse)
mydf <- tibble(mtcars)
Say I want all the observations who share cyl+am+vs The following code does not work:
mydf |> filter(mpg %in%
mydf |> filter(duplicated(paste0(cyl,am,vs))) |> pull(mpg)
)
Error:
Error in `filter()`:
ℹ In argument: `pull(...)`.
Caused by error in `UseMethod()`:
! no applicable method for 'filter' applied to an object of class "logical"
However, the same structure, using a variable work:
mpg_as_var <- mydf |> filter(duplicated(paste0(cyl,am,vs))) |> pull(mpg)
mydf |> filter(mpg %in% mpg_as_var)
I don't want to just take the duplicates, but also the first duplicated observations. otherwise it would've been a simple filter(duplicated()) query
Got any ideas?