David
David

Reputation: 329

User-defined function with no arguments, in R, in pipe

I would like to write a function that does not have arguments, and that can be referenced in a pipe (%>%), so I don't have to repeat several lines of code. However, I'm not getting it after multiple tries. I would also appreciate help on writing a function referred to in a pipe, with arguments. Many thanks for any help! Simplified example follows:

library(tidyverse)
a <- c(1:10)
b <- c(11:20)
c <- data.frame(a, b)
c
#>     a  b
#> 1   1 11
#> 2   2 12
#> 3   3 13
#> 4   4 14
#> 5   5 15
#> 6   6 16
#> 7   7 17
#> 8   8 18
#> 9   9 19
#> 10 10 20
y <- function() {
  filter(d<5)
}

c %>% mutate(d = a*b) %>% y()
#> Error in y(.): unused argument (.)

Created on 2020-08-16 by the reprex package (v0.3.0)

Upvotes: 0

Views: 570

Answers (1)

daniellga
daniellga

Reputation: 1224

pipe considers the first argument of the function is the data, for example the first arguments of mutate or filter are both the data. So when you do mtcars %>% mutate(a = 5) you are actually doing mutate(mtcars, a = 5).

So you would have to modify it to:

y <- function(data) {
  filter(data, d < 80)
}

c %>% mutate(d = a*b) %>% y()

  a  b  d
1 1 11 11
2 2 12 24
3 3 13 39
4 4 14 56
5 5 15 75

Upvotes: 1

Related Questions