littleworth
littleworth

Reputation: 5169

How to assign partial parameters from a dataframe on purrr pmap function

I have the following data frame

library(tidyverse)

param_df <- data.frame(
  y_high = 10:12,
  x = 1:3 + 0.1,
  y = 3:1 - 0.1,
  z = letters[1:3]
) %>% 
  as.tibble() %>% 
  mutate(z =  as.character(z))

param_df
#> # A tibble: 3 x 4
#>   y_high     x     y z    
#>    <int> <dbl> <dbl> <chr>
#> 1     10  1.10 2.90  a    
#> 2     11  2.10 1.90  b    
#> 3     12  3.10 0.900 c

And the following function

  myfunc <- function(x=NULL, y=NULL, z=NULL) {
  # The function is simpy printing the sum
  cat(" The sum of ", z ," is ", x + y , "\n")
}

What the function does is to take only x and y columns from param_df and simply print the sum.

I tried this

param_df %>%
  purrr::pmap(myfunc, x = x, y = y, z=z)

# # Later would like to have the flexibility to do 
# param_df %>%
#  purrr::pmap(myfunc, x = x, y = y_high, z=z)

But it gives the following error message:

Error in .f(x = .l[[c(1L, i)]], y = .l[[c(2L, i)]], z = .l[[c(3L, i)]],  : 
  formal argument "x" matched by multiple actual arguments

What's the right way to do it?

The desired final output with purrr::pmap is

The sum a is 4
The sum b is 4
The sum c is 4

Upvotes: 1

Views: 182

Answers (1)

Paul
Paul

Reputation: 9087

Your function only has side effects, so you want walk rather than map.

walk2 will take 2 arguments and apply a function.

purrr::walk2(param_df$x, param_df$y, myfunc)
# The sum is  4 
# The sum is  4 
# The sum is  4 

Edit: For your example.

myfunc <- function(x=NULL, y=NULL, z=NULL) {
  # The function is simpy printing the sum
  cat(" The sum of ", z ," is ", x + y , "\n")
}

param_df %>%
  with(
    pwalk(list(x, y, z), .f = myfunc))
 # The sum of  a  is  4 
 # The sum of  b  is  4 
 # The sum of  c  is  4 

Or, with magrittr special pipes.

library('magrittr')

param_df %$%
  pwalk(list(x, y, z), .f = myfunc)
#  The sum of  a  is  4 
#  The sum of  b  is  4 
#  The sum of  c  is  4 

Upvotes: 2

Related Questions