3

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.

Alex
  • 2,603
  • 4
  • 40
  • 73

1 Answers1

3

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    This is great! I have never seen `enquo` or `!!`. Where can I find more documentation? – Alex Oct 18 '17 at 03:05
  • 2
    @Alex new version of dplyr https://blog.rstudio.com/2017/06/13/dplyr-0-7-0/ – BENY Oct 18 '17 at 03:10
  • 2
    Also see the [dplyr programming vignette](https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html). – eipi10 Oct 18 '17 at 03:17
  • This still does not seem to add the data to the original table. For example `sim %>% addr(x,n)` followed by `sim` yields only a 2 column table not 3 columns. – Alex Oct 18 '17 at 10:52
  • 1
    @Alex You need to assign it to original data i.e. `sim <- addr(sim, x, n)`. There is also the magrittr operator `%<>%` which does it. – akrun Oct 18 '17 at 10:52