I would like to add an additional column to an existing dataframe by mutating the optimized result from the OPTIM() function. The code works when I strip the dataframe down to 1 row, but gives the following error when there are 2 rows:
Caused by error in optim()
:
! objective function in optim evaluates to length 2 not 1
library(tidyverse)
library(dbplyr)
hfcn <- function(b, D, U, U2, U3){
Din = ((1 - D)^-b - 1) / b
rsd_2 = ((U / (1 + b*Din*2)^(1/b) - U2)^2)^0.5
rsd_3 = ((U / (1 + b*Din*3)^(1/b) - U3)^2)^0.5
rst_tot = rsd_2 + rsd_3
return(rst_tot)
}
#################################
#### If I create dataframe A with a single row, the code works, but fails when there are 2 rows ####
# A <- data.frame(ID = c("A1")
# , U = c(28844)
# , D = c(0.7941582)
# , U2 = c(3417)
# , U3 = c(2465)
# )
#################################
A <- data.frame(ID = c("A1", "A2")
, U = c(72625, 28844)
, D = c(0.7785440, 0.7941582)
, U2 = c(7916, 3417)
, U3 = c(5409, 2465)
)
A2 <- mutate(A
, C = optim(par = 1.1
, hfcn
, D = A$D
, U = A$U
, U2 = A$U2
, U3 = A$U3
, method = "BFGS"
#, method = "L-BFGS-B"#, lower = 0, upper = 3
)[1]
)
Error in mutate()
:
! Problem while computing C = ...[]
.
Caused by error in optim()
:
! objective function in optim evaluates to length 2 not 1
Backtrace:
- dplyr::mutate(...)
- stats::optim(...)
I have successfully run the code when I limit the database to a single row. I can run both rows independently through the function and mutate and additional column using OPTIM(), so the code and function inputs check out. I suspect I may have to use a function from purrr but I cannot find anything online that helps me with this problem.