mt1022
mt1022

Reputation: 17289

Error in subsetting with $ immediately after a function in dplyr pipe

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.

Upvotes: 6

Views: 3344

Answers (1)

mt1022
mt1022

Reputation: 17289

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

Upvotes: 3

Related Questions