将函数从 mapply 迁移到 tibble rowwise

Migrate a function from mapply to tibble rowwise

将 user-defined-function 从与 mapply 一起使用转换为与 tibble rowwise.

一起使用所需的任何提示技巧或咒语,我将不胜感激

这个最小的可重现示例基于问题

具体来说,我有一个调用 uniroot 的函数,它可以与 mapply 一起正常工作。 但是,当它与 tibble/data-frame.

一起使用时它会中断
values <- tibble(a=1:3, b=4:6)
class(values)

f_1 <- function(a, x = x_default, b = b_default, y = y_default, ...){
  x - a
}

f_2 <- function(a, x, b, y){
  value_a   <- uniroot(f_1, lower=-b*100, upper=b * 100, extendInt="no", tol=0.0001, trace = 20, maxiter=1000, check.conv=TRUE,
                          x=x, b=b, y=y)
}

newCF <- partial(f_2, x=10 , y=15)
values %>% 
  mutate( newCF( a = values$a, b = values$b ) )

x=10
y=15
mapply( f_2, values$a, x=x, values$b, y=y )

mapply 的结果是:

> mapply( f_2, values$a, x=x, values$b, y=y )
       [,1] [,2] [,3]
root       10   10   10
f.root     0    0    0
iter       1    1    1
init.it    NA   NA   NA
estim.prec 410  510  610

使用小标题的结果是:

> values %>%
+   mutate( newCF( a = values$a, b = values$b ) )
Error in mutate_impl(.data, dots) :
  Evaluation error: f() values at end points not of opposite sign.
In addition: Warning messages:
1: In if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
  the condition has length > 1 and only the first element will be used
2: In if (is.na(f.upper)) stop("f.upper = f(upper) is NA") :
  the condition has length > 1 and only the first element will be used
7: doTryCatch(return(expr), name, parentenv, handler)
6: tryCatchOne(expr, names, parentenv, handlers[[1L]])
5: tryCatchList(expr, classes, parentenv, handlers)
4: tryCatch(.External2(C_zeroin2, function(arg) f(arg, ...), lower,
       upper, f.lower, f.upper, tol, as.integer(maxiter)), warning = function(w) w)
3: uniroot(f_1, lower = -b * 100, upper = b * 100, extendInt = "no",
       tol = tolerance, trace = 20, maxiter = 1000, check.conv = TRUE,
       x = x, b = b, y = y) at #2
2: (function (a, x, b, y)
   {
       value_a <- uniroot(f_1, lower = -b * 100, upper = b * 100,
           extendInt = "no", tol = tolerance, trace = 20, maxiter = 1000,
           check.conv = TRUE, x = x, b = b, y = y)
   })(dots[[1L]][[1L]], x = dots[[2L]][[1L]], dots[[3L]][[1L]],
       y = dots[[4L]][[1L]])

解决方案不需要使用partial,如下:

library(purr)
values %>% 
  bind_cols(pmap_df(list(a=.$a, b=.$b), f_2, x=10 , y=15))

希望对某人有所帮助。