While I have a (somewhat convoluted) work-around, I'm trying to figure out why subsetting with square brackets ([]) does not work the same when piping results from dplyr functions.
For a really simple demonstration. The first two work:
library(dplyr)
my_data <- mtcars %>%
filter(qsec == 16.46)
my_data[,"gear"]
#[1] 4
filter(mtcars, qsec == 16.46)[,"gear"]
#[1] 4
However, the following fails:
mtcars %>% filter(qsec == 16.46)[,"gear"]
#Error in filter(qsec == 16.46) : object 'qsec' not found
I can't seem to find anything that will allow this notation to work. I can get around it by doing some things like:
mtcars %>%
filter(qsec == 16.46) %>%
select(gear) %>%
as.numeric()
#[1] 4
mtcars %>%
filter(qsec == 16.46) %>%
subset(subset = TRUE, select = "gear") %>%
as.numeric()
#[1] 4
But that's adding minimum of two piped functions (depending on what you are needing to subset), and it seems like the square bracket notation should work, but does not, at least, not in the way I expect.
Any insight on why filter(mtcars, qsec == 16.46)[,"gear"]
works,
but mtcars %>% filter(qsec == 16.46)[,"gear"]
does not?