【问题标题】:Apply a function over list of Dataframes using optim()使用 optim() 在数据框列表上应用函数
【发布时间】: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)

【问题讨论】:

    标签: r function lapply


    【解决方案1】:

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

    【讨论】:

    • 不准确是什么意思?鉴于您的问题,尚不清楚数据框中的任何其他值(即“动物”和“年”)如何或是否影响长度和高度,因此我只是提取了优化 / f 函数中使用的那些数据对。请详细说明。
    • 好的,看来您删除了您的评论,即问题解决了吗?
    • 问题没有解决。当您运行我提供的代码时,您会得到下面提供的结果,这些结果是正确的,使用您提供的代码,它们不会产生相同的正确值: $par [1] 10.465813 1.038046 $value [1] 0.03611693 $counts function gradient 97 NA $convergence [1] 0 $message NULL
    • 啊,我明白了,对不起,我认为重量和长度对是个人的。请检查我的编辑以使用 for 循环快速修复。
    • 非常好,谢谢。这正是我想要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多