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

I could multiply one column with the following syntax for functions that return data.frameeither list:

library(dplyr)
filter(mtcars, disp > 400)$mpg
# [1] 10.4 10.4 14.7

But this leads to 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 it $does not work when used in a pipe, as in the above example.

+4
source share
1 answer

I think I figured out the reason.

When I call filter(mtcars, disp > 400)$mpgwhat actually happens:

`$`(filter(mtcars, disp > 400), mpg)
# [1] 10.4 10.4 14.7

Similarly, mtcars %>% filter(disp > 400)$mpginterpreted as:

`$`(mtcars, filter(disp > 400), mpg)

lhs of %>% rhs. , $ 2 , 3 .

# Error in mtcars$filter(disp > 400) : 
#   3 arguments passed to '$' which requires 2

. mtcars data.frame filter(disp > 400) : mtcars$filter(disp > 400).

+2

Source: https://habr.com/ru/post/1683090/


All Articles