I could subset a single column with the following syntax for functions that return data.frame
or list
:
library(dplyr)
filter(mtcars, disp > 400)$mpg
# [1] 10.4 10.4 14.7
But this causes the following error when used in a pipe (%>%
):
mtcars %>% filter(disp > 400)$mpg
# Error in .$filter(disp > 400) :
# 3 arguments passed to '$' which requires 2
I would like to know why $
does not work when used in pipe like the above example.
I think I have figured out the reason.
When I call filter(mtcars, disp > 400)$mpg
, what actually happen is:
`$`(filter(mtcars, disp > 400), mpg)
# [1] 10.4 10.4 14.7
Similarly, mtcars %>% filter(disp > 400)$mpg
is interpreted as:
`$`(mtcars, filter(disp > 400), mpg)
, because lhs of %>%
will be the first argument of the function at rhs. This reproduced the same error that $
requires 2 args while 3 were supplied.
# Error in mtcars$filter(disp > 400) :
# 3 arguments passed to '$' which requires 2
The error message also verified the above speculation. mtcars
is used as the data.frame name and filter(disp > 400)
is treated as a column name: mtcars$filter(disp > 400)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With