no_op: Pipe-friendly no-operation function

Description Usage Arguments Details Value Examples

Description

returns the first input with side effects

Usage

1
no_op(.x, .expr, ..., .check_fun = TRUE)

Arguments

.x

any R object

.expr

R expression that produces side effects

..., .check_fun

see 'details'

Details

no_op is a pipe-friendly function that takes any values in, evaluate expressions but still returns input. This is very useful when you have the same input across multiple functions and you want to use pipes.

.expr is evaluated with a special object '.', you can use '.' to represent .x in .expr. For example, if .x=1:100, then plot(x=seq(0,1,length.out = 100), y=.) is equivalent to plot(x=seq(0,1,length.out = 100), y=1:100).

.check_fun checks whether .expr returns a function, if yes, then the function is called with argument .x and ...

Value

The value of .x

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
library(magrittr)

## 1. Basic usage

# Will print('a') and return 'a'
no_op('a', print)

# Will do nothing and return 'a' because .check_fun is false
no_op('a', print, .check_fun = FALSE)

# Will print('a') and return 'a'
no_op('a', print(.), .check_fun = FALSE)

## 2. Toy example
library(graphics)

par(mfrow = c(2,2))
x <- rnorm(100)

# hist and plot share the same input `rnorm(100)`

x %>%
  # .expr is a function, all ... are passed as other arguments
  no_op( hist, nclass = 10 ) %>%
  no_op( plot, x = seq(0,1,length.out = 100) ) %>%

  # Repeat the previous two plots, but with different syntax
  no_op({ hist(., nclass = 10) }) %>%
  no_op({ plot(x = seq(0,1,length.out = 100), y = .) }) %>%

  # The return statement is ignored

  no_op({ return(x + 1)}) ->
  y

# x is returned at the end

identical(x, y)   # TRUE

dipsaus documentation built on Sept. 6, 2021, 5:08 p.m.