Я использовал safely
, чтобы поймать ошибку, которая возникает в моем коде, когда я мурлычу. Однако результат safely
намного сложнее, чем я ожидал.
Сначала мы создаем необходимые функции и примеры данных.
#base functions.
SI_tall <- function(topheight, age, si ){
paramasi <- 25
parambeta <- 7395.6
paramb2 <- -1.7829
refAge <- 100
d <- parambeta*(paramasi^paramb2)
r <- (((topheight-d)^2)+(4*parambeta*topheight*(age^paramb2)))^0.5
## height at reference age
h2 <- (topheight+d+r)/ (2+(4*parambeta*(refAge^paramb2)) / (topheight-d+r))
return(abs(h2 - si))
}
new.topheight <- function(my.si, my.age){
optim(par = list(topheight = 10), ## this topheight is just an initial value
method = 'L-BFGS-B', fn = SI_tall, si = my.si, age = my.age, lower= 0, upper=100)$par
}
#Creating the function which will display errors.
safe_new.topheight <- safely(new.topheight)
#Creating data
my.age <- seq(0,100, by=0.2)
my.si <- c(15)
si.crossing <- tidyr::crossing(my.si, my.age) %>% data.frame()
#Creating the column to be unnested.
si.crossing2<- si.crossing %>%
mutate(height=map2(my.si,my.age, safe_new.topheight))
Тем не менее, результат становится сложным для меня, чтобы разложить - я даже не знаю, насколько далеко заходит вложенность списков в столбце «высота». Вот вывод первых 5 строк в моих данных:
structure(list(my.si = c(15, 15, 15, 15, 15), my.age = c(0, 0.2,
0.4, 0.6, 0.8), height = list(list(result = NULL, error = structure(list(
message = "L-BFGS-B needs finite values of 'fn'", call = optim(par = list(topheight = 10),
method = "L-BFGS-B", fn = SI_tall, si = my.si, age = my.age,
lower = 0, upper = 100)), class = c("simpleError", "error",
"condition"))), list(result = c(topheight = 0.000693170450744849),
error = NULL), list(result = c(topheight = 0.00205917508142004),
error = NULL), list(result = c(topheight = 0.00390099534708239),
error = NULL), list(result = c(topheight = 0.00639475141226834),
error = NULL))), row.names = c(NA, 5L), class = "data.frame")
Есть ли способ сгладить это до столбцов:
my.si, my.age, topheight, error.
Большое спасибо!