Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

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.

like image 732
mt1022 Avatar asked Oct 18 '22 08:10

mt1022


1 Answers

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

like image 187
mt1022 Avatar answered Nov 15 '22 07:11

mt1022