【发布时间】:2018-02-15 15:40:24
【问题描述】:
我正在尝试找出一种通过优化函数运行许多数据帧列表的方法。我目前必须逐个数据帧才能使其正常工作,如下面的给定代码所示。任何帮助如何使用 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)
【问题讨论】: