I'm trying to compute a function whose arguments are names of a column in a data frame. I need to loop over each row and compute the function. It seems pmap is a neat way to do this, but I'm forced to specify the " ..1, ..2, " notation to indicate column positions in the data frame. That's not a very reproducible way of running this I think.
Although, it just knows the names of the columns when I use an anonymous function, instead of a named one.
library(purrr)
#> Warning: package 'purrr' was built under R version 3.6.3
toy_df <- data.frame(a = 1:10, b = 2:11, c = 3:12)
toy_function <- function(a, b, c) {
data.frame(result = a^2 + b^3 + log(a)*c + sin(a)*b)
}
## this fails
toy_fail <- purrr::pmap(toy_df, ~ toy_function())
#> Error in data.frame(result = a^2 + b^3 + log(a) * c + sin(a) * b): argument "a" is missing, with no default
## this works
toy_pass <- purrr::pmap(toy_df, ~ toy_function(..1, ..2, ..3))
## this works and I didn't need to specify the positions
toy_also_pass <- purrr::pmap(toy_df, function(a, b, c){
data.frame(result = a^2 + b^3 + log(a)*c + sin(a)*b)
})
Created on 2020-07-28 by the reprex package (v0.3.0)