10

Apologies for what might be a very simple question.

I am new to using the purrr package in R and I'm struggling with trying to pass a second parameter to a function.

library(dplyr)
library(purrr)

my_function <- function(x, y = 2) {
  z = x + y
  return(z)
}

my_df_2 <- my_df %>%
  mutate(new_col = map_dbl(.x = old_col, .f = my_function))

This works and most often I don't need to change the value of y, but if I had to pass a different value for y (say y = 3) through the mutate & map combination, what is the syntax for it?

Thank you very much in advance!

www
  • 38,575
  • 12
  • 48
  • 84
elvikingo
  • 947
  • 1
  • 11
  • 20

2 Answers2

13

The other idea is to use the following syntax.

library(dplyr)
library(purrr)

# The function
my_function <- function(x, y = 2) {
  z = x + y
  return(z)
}

# Example data frame
my_df <- data_frame(old_col = 1:5)

# Apply the function   
my_df_2 <- my_df %>%
  mutate(new_col = map_dbl(old_col, ~my_function(.x, y = 3)))

my_df_2
# # A tibble: 5 x 2
# old_col new_col
#     <int>   <dbl>
# 1       1      4.
# 2       2      5.
# 3       3      6.
# 4       4      7.
# 5       5      8.
www
  • 38,575
  • 12
  • 48
  • 84
  • 2
    what is the purpose of ~ here? – ktyagi Mar 28 '19 at 16:26
  • 1
    Late answer but in case anyone else is wondering - within the context of [purrr](https://purrr.tidyverse.org/) functions `~` is shorthand for creating an inline anonymous function. See [this explanation](https://adv-r.hadley.nz/functionals.html#purrr-shortcuts) from Advanced R for more info – Chris Greening Jun 22 '22 at 21:08
5

I think all you need to do is modify map_dbl like so:

library(dplyr)
library(purrr)

df <- data.frame(a = c(2, 3, 4, 5.5))

my_function <- function(x, y = 2) {
  z = x + y
  return(z)
}

df %>%
  mutate(new_col = map_dbl(.x = a, y = 3, .f = my_function))
    a new_col
1 2.0     5.0
2 3.0     6.0
3 4.0     7.0
4 5.5     8.5
tyluRp
  • 4,678
  • 2
  • 17
  • 36
  • 1
    I don't see why it was necessary to remove the default value of the `y` argument in `my_function`? The rest of the answer is good. – Marius Apr 09 '18 at 01:41
  • Your right, it works either way. If OP usually has 2 as the default value (which seems to be the case) I should probably modify my answer as so. I just like to keep the function as minimal as possible. – tyluRp Apr 09 '18 at 01:44
  • Np, happy to help @user1823293 – tyluRp Apr 09 '18 at 01:48