4

Here's a dummy example of what bothers me (in a vanilla session):

library(magrittr)
"test" %>% is.na()
#[1] FALSE
"test" %>% nchar()>3
#[1] TRUE
"test" %>% is.na(.)
#[1] FALSE
"test" %>% nchar(.)>3
#[1] TRUE
"test" %>% is.na(.) || nchar(.)>3
#Error in nchar(.) : object '.' not found

My understanding so far is that . operator (don't know if the word operator is accurate, but let's go with it) can be used only in the first function called after pipe-forward.

useless_function <- function(a, b, c) {
    print(c(a,b,c))
    return(FALSE)
}
"test" %>% useless_function(1, "a")
#[1] "test" "1"    "a"   
#[1] FALSE
"test" %>% useless_function(1, "a", .)
#[1] "1"    "a"    "test"
#[1] FALSE
"test" %>% useless_function(., ., "a")
#[1] "test" "test" "a"   
#[1] FALSE
"test" %>% useless_function("a", ., useless_function(1, 2, .))
#[1] "1"    "2"    "test"
#[1] "a"     "test"  "FALSE"
#[1] FALSE
"test" %>% useless_function("a", ., useless_function(1, 2, .)) || useless_function(., "never", "here")
#[1] "1"    "2"    "test"
#[1] "a"     "test"  "FALSE"
#Error in print(c(a, b, c)) : object '.' not found

So, I've tried to use magrittr::or function:

> "test" %>% or(is.na(.), nchar(.)>3)
#Error in or(., is.na(.), nchar(.) > 3) : 
#  3 arguments passed to '|' which requires 2

and that's pretty much where I'm stuck.

Note that I know a few ways around this problem. Just, none of them is as clear as normal pipe-forward function.

("test" %>% is.na()) | ("test" %>% nchar()>3)
#[1] TRUE
"test" ->.; is.na(.) | nchar(.)>3 # Don't hit me, this one is just for fun
#[1] TRUE
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
Vongo
  • 1,325
  • 1
  • 17
  • 27
  • 5
    `"test" %>% {is.na(.) || nchar(.)>3}` should do the trick :) – piptoma Nov 12 '19 at 08:01
  • The `"test %>%` part of your code is only referenced by `is.na(.)`. This is why you are getting the `object '.' not found` error message. Although you should not write code like this, try and take a look at this: `"test" %>% is.na(.) || "test" %>% nchar(.) > 3`. – larsoevlisen Nov 12 '19 at 08:11

1 Answers1

4

Use {} to specify the precedence, so that they are evaluated the way you want

library(magrittr)

"test" %>% {is.na(.) || nchar(.)>3}
#[1] TRUE

Or

"test" %>% {or(is.na(.), nchar(.)>3)}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213