0

I'd like to create a function that works inside of mutate. As a simple example, I can get this to work:

library(tidyverse)

# Toy Data
df <- tibble::tribble(
  ~id, ~first_name, ~gender, ~height,
  1,   "john",      "m",     71,
  2,   "jane",      "f",     64,
  3,   "sally",     "f",     65
)

double_it <- function(df, x) {
  x <- enquo(x)
  pull(df, !!x) * 2
}

df %>% mutate(height_2 = double_it(., height))

# A tibble: 3 x 5
     id first_name gender height height_2
  <dbl> <chr>      <chr>   <dbl>    <dbl>
1     1 john       m          71      142
2     2 jane       f          64      128
3     3 sally      f          65      130

But, what I'd like to get to is this:

double_it <- function(x) {
  ???
}

df1 %>% mutate(height_2 = double_it(height))

# A tibble: 3 x 5
     id first_name gender height height_2
  <dbl> <chr>      <chr>   <dbl>    <dbl>
1     1 john       m          71      142
2     2 jane       f          64      128
3     3 sally      f          65      130
Nettle
  • 3,193
  • 2
  • 22
  • 26
Brad Cannell
  • 3,020
  • 2
  • 23
  • 39
  • So you just want `double_it <- function(x) {x*2}`? `dplyr` can use any simple function in the `mutate()`. – MrFlick Oct 16 '18 at 19:44
  • This was a bad example to demonstrate my problem. I'm going to try again. – Brad Cannell Oct 16 '18 at 19:54
  • It looks like you just need to write a normal function? – Lionel Henry Oct 16 '18 at 22:18
  • Thanks, @lionel. You are right. I tried to create a simple example that would have the same problem I’m trying to solve. But, I ended up making it too simple. I will post a better example when I get some time. – Brad Cannell Oct 16 '18 at 22:32

1 Answers1

1

You could use .data$ as prefix:

library(tidyverse)

# Toy Data
df1 <- tibble::tribble(
  ~id, ~first_name, ~gender, ~height,
  1,   "john",      "m",     71,
  2,   "jane",      "f",     64,
  3,   "sally",     "f",     65
)

double_it <- function(x) {
  x * 2
}

df1 %>% mutate(height_2 = double_it(.data$height))
#> # A tibble: 3 x 5
#>      id first_name gender height height_2
#>   <dbl> <chr>      <chr>   <dbl>    <dbl>
#> 1     1 john       m          71      142
#> 2     2 jane       f          64      128
#> 3     3 sally      f          65      130

or just use height directly:

double_it <- function(x) {
  x * 2
}

df1 %>% mutate(height_2 = double_it(height))
#> # A tibble: 3 x 5
#>      id first_name gender height height_2
#>   <dbl> <chr>      <chr>   <dbl>    <dbl>
#> 1     1 john       m          71      142
#> 2     2 jane       f          64      128
#> 3     3 sally      f          65      130
Daniel
  • 7,252
  • 6
  • 26
  • 38
  • Thanks, @Daniel. My fault, this was actually a bad example of the real problem I'm trying to solve. I'm going to edit the code above. – Brad Cannell Oct 16 '18 at 19:55