Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass second parameter to function while using the map function of purrr package in R

Tags:

r

purrr

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!

like image 794
elvikingo Avatar asked Apr 09 '18 01:04

elvikingo


2 Answers

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.
like image 79
www Avatar answered Oct 20 '22 00:10

www


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
like image 28
tyluRp Avatar answered Oct 20 '22 00:10

tyluRp