I can't figure this 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 find it confusing that all(.$b)
doesn't work. That doesn't seem intuitive to me at all.
Well, the %>%
operator is borrowed from the magrittr
package which defines the following rules:
You can see that the whole data frame is still being passed in as the first parameter with 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 are getting both the data.frame and the vector (the function is receiving two parameters). I believe this is because you are not moving the .
to a position other than the first parameter so you are not changing the behavior to pass along the object as the first parameter.
It just so happens that the magrittr
package has a different operator for use in cases like this. You can use %$%
.
library(magrittr)
dat %$% all(b)
# [1] TRUE
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