Vongo
Vongo

Reputation: 1434

Passing an argument twice with magrittr pipe-forward operator

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

Upvotes: 5

Views: 480

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388907

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

Upvotes: 4

Related Questions