Search code examples
rdplyrmagrittr

Adding a column to custom piped function


I am new to making functions that take advantage of %>% in R.

Given the following data

sim <- tribble(~x,~n,1,1,1,2,1,3)

I would like to make a function that adds a column like so

>sim <- sim %>% mutate(sum = x+n)
>sim
# A tibble: 3 x 3
      x     n   sum
  <dbl> <dbl> <dbl>
1     1     1     2
2     1     2     3
3     1     3     4

This is as far as made it

addr <- function(tbl, x, n){tbl <- mutate(sumr=tbl$x+tbl$n)}
sim <- tribble(~x,~n,1,1,1,2,1,3)
sim %>% addr(x,n)

The problem is that I am not adding a column onto the piped table.


Solution

  • We can create a function using the tidy way

    addr <- function(dat, col1, col2) {
      col1 <- enquo(col1)
      col2 <- enquo(col2)
      dat %>%
           mutate(sum = (!!col1) + (!!col2))
    }
    
    addr(sim, x, n)
    # A tibble: 3 x 3
    #      x     n   sum
    #   <dbl> <dbl> <dbl>
    #1     1     1     2
    #2     1     2     3
    #3     1     3     4