Weirdness with dplyr and all

I can’t figure it out.

library(dplyr) dat <- data.frame(a = 1:5,b = rep(TRUE,5)) # this doesn't work dat %>% all(.$b) # tricky # this doesn't work dat %>% all(b) # # this does dat %>% .$b %>% all 

I am confused that all(.$b) not working. This does not seem intuitive to me.

+5
source share
1 answer

Well, the %>% operator is borrowed from the magrittr package, which defines the following rules :

  • By default, the left side (LHS) will be passed as the first argument to the function that appears on the right side (RHS).
  • When LHS is required at a position other than the first, the dot "." as a placeholder.

You can see that the entire data frame is still being passed as the first parameter in this example.

 f<-function(...) str(list(...)) dat %>% f(.$b) # $ :'data.frame': 5 obs. of 2 variables: # ..$ a: int [1:5] 1 2 3 4 5 # ..$ b: logi [1:5] TRUE TRUE TRUE TRUE TRUE # $ : logi [1:5] TRUE TRUE TRUE TRUE TRUE 

So, you get both data.frame and vector (the function takes two parameters). I believe that this is due to the fact that you are not moving . to a position other than the first parameter, so you do not change the behavior to walk through the object as the first parameter.

It so happened that the magrittr package has a different operator for use in such cases. You can use %$% .

 library(magrittr) dat %$% all(b) # [1] TRUE 
+6
source

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


All Articles