繁体   English   中英

使用optim()将函数应用于数据框列表

[英]Apply a function over list of Dataframes using optim()

我试图找出一种通过优化功能运行许多数据帧列表的方法。 我目前必须逐个数据帧地运行才能使其正常工作,如下面的给定代码所示。 对如何使用lapply或for loop自动执行此过程有帮助吗? 谢谢。

# required library
library(dplyr)

A <- "Cheetah 1"
B <- 2018
C <- c(0, 9.14, 18.29, 36.58)
D <- c(.2, 1.71, 2.71, 4.52)

Measured <- as.data.frame(cbind(A, B, C, D))
colnames(Measured) <- c('Animal', 'Year', 'Length', 'Height') 

H <- "Cheetah 2"
I <- 2018
J <- c(0, 9.14, 18.29, 36.58)
K <- c(.2, 1.78, 2.81, 4.61)

Measured2 <- as.data.frame(cbind(H, I, J, K))
colnames(Measured2) <- c('Animal', 'Year', 'Length', 'Height') 

Measured3 <- rbind(Measured, Measured2)
Measured3 <- split(Measured3, Measured3$Animal)

Measured3 <- lapply(Measured3, function(x){
x %>% 
   mutate(Length = as.numeric(as.character(Length)),
       Height = as.numeric(as.character(Height)))
 })

#initialize values
Var1 = 15
Var2 = 5

x0 = c(Var1,Var2)


#define function to optimise: optim will minimize the output
f <- function(x, a, b) {


y=0
#variables will be optimise to find the minimum value of f

V_1 = x[1]
V_2 = x[2]

 Predicted_X <- V_1 * (a - V_2 + V_2*exp(-a/V_2))

  y = sum((Predicted_X - b)^2)

    return(y)

 }

Y <- optim(x0, f, a = Measured3$`Cheetah 1`$Height,  b =  Measured3$`Cheetah 1`$Length)

您可以使用以下for循环进行快速修复:

nr_cheetahs <- length(Measured3)
optim_results <- vector("list", nr_cheetahs) 
for (i in seq(1, nr_cheetahs)){
 optim_results[[i]] <- optim(par=x0, fn=f, a=Measured3[[i]]['Height'], b=Measured3[[i]]['Length'])
}

# optim_results[[1]] provides the same result as your Y

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM