使用optim()在Dataframe列表上应用函数

时间:2018-02-13 21:50:10

标签: r function lapply

我试图想出一种通过优化函数运行许多数据帧列表的方法。我目前不得不通过数据帧去数据帧以使其正常工作,如下面给出的代码所示。有关如何使用lapply或for循环自动执行此过程的任何帮助?谢谢。

# 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)

1 个答案:

答案 0 :(得分:0)

您可以使用以下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