Easily keep track of inputs and outputs of a function safely applied to each row of a data frame. Output is rectangularized into the original data frame for easy analysis.
pmap_safely(.d, .f)
.d | A data frame with the inputs to .f. |
---|---|
.f | A function to apply to each row of .d. |
# a function to apply calculate_if_positive <- function(a, b){ if(a < 0 & b < 0) {stop("Both numbers are negative.")} else if(a < 0) {stop("Just the first number is negative")} else if(b < 0) {stop("Just the second number is negative")} list(add = a + b, subtract = a - b, multiply = a * b, divide = a / b) } # data frame to apply the function to by row numbers <- data.frame(a = c(-1, 0, 1, 2), b = c(2, 1, 0, -1), irrelevant = c("minneapolis", "st_paul", "minneapolis", "st_paul")) # apply pmap_safely(numbers, calculate_if_positive)#>#> a b irrelevant error result #> 1 -1 2 minneapolis Just the first number is negative NULL #> 2 0 1 st_paul <NA> 1, -1, 0, 0 #> 3 1 0 minneapolis <NA> 1, 1, 0, Inf #> 4 2 -1 st_paul Just the second number is negative NULL