Reputation: 1111
I'm trying to map a function to multiple inputs contained in
rows of a dataframe using purrr::pmap
. I've got a reprex
below:
library(tidyverse)
# Create dummy data
e <- 0.3
f <- 1:3
g <- 1:3
df <- tidyr::crossing(e = e, f = f, g = g)
# Create a simple function to use
new_ratio <- function(x, y, z){
return(x/(y + z))
}
# Apply pmap across rows of the dataframe `df` - not working as intended
purrr::pmap(df, ~ new_ratio(x = e, y = f, z = g))
#> [[1]]
#> [1] 0.150 0.075 0.050
#>
#> [[2]]
#> [1] 0.150 0.075 0.050
#>
#> [[3]]
#> [1] 0.150 0.075 0.050
#>
#> [[4]]
#> [1] 0.150 0.075 0.050
#>
#> [[5]]
#> [1] 0.150 0.075 0.050
#>
#> [[6]]
#> [1] 0.150 0.075 0.050
#>
#> [[7]]
#> [1] 0.150 0.075 0.050
#>
#> [[8]]
#> [1] 0.150 0.075 0.050
#>
#> [[9]]
#> [1] 0.150 0.075 0.050
Created on 2018-07-16 by the reprex package (v0.2.0).
As it can be seen I really want to create a simple output
row by row to give the ratio e/(f+g)
in this
simple example. The function keeps returning the same values
for different inputs. In the first row, I would expect the
output 0.3/(1 + 1) = 0.15
, in the second row would expect
0.3/(1 + 2) = 0.1
etc
Could anyone please show how to correct for this? I am not quite
understanding how to apply pmap
from the documentation
Upvotes: 3
Views: 848
Reputation: 886938
We can change the column names to the argument names and it should work
pmap_dbl(setNames(df, c('x', 'y', 'z')), new_ratio)
#[1] 0.150 0.100 0.075 0.100 0.075 0.060 0.075 0.060 0.050
Or if we intend to use ~
, the arguments are ..
followed by the number
pmap_dbl(df, ~ new_ratio(x = ..1, y= ..2, z = ..3))
#[1] 0.150 0.100 0.075 0.100 0.075 0.060 0.075 0.060 0.050
Upvotes: 1