簡體   English   中英

在r中使用for循環將最佳函數應用於函數

[英]apply an optimal function to a function using a for loop in r

我編寫了一個簡單的函數來獲得最大的可能性,並且希望該函數在R中使用for循環根據其參數的不同值給出不同的結果。這就是我的函數包括一個基於for循環的表達式。 我的函數運行良好,結果保存在列表中。 然后,由於有兩個不同的結果,因此我想根據函數的每個部分將optim函數應用於函數。 例如,

ff <- function(x,mu=c(2,0.5),sd=c(0.2,0.3)){
  out <- vector("list",2)
  for (i in 1:2){
    out[[i]] <- -sum(log(dnorm(x,mu[[i]],sd[[i]]))) ## here I have two different part of my funcitons wrap as one using for loop.
  }
return(out)
}


 set.seed(123)
    x <- rnorm(10,2,0.5)
    x

那么我的功能的結果是:

> ff(x)
[[1]]
[1] 25.33975

[[2]]
[1] 101.4637

然后,由於我的函數使用for循環將兩個不同的部分包裝為一個部分,因此我希望基於函數的每個部分將optim函數應用於該函數。 我嘗試了很多自己的方法,但是它們沒有用。 這是我的嘗試之一:

op <- vector("list",2)
for(i in 1:2){

op <- optim(c(0.5,0.5),fn=ff[[i]],i=i)
}

也就是說,我希望optim功能在我的參數的第一個值評估我函數i=1 ,然后評價函數為所述第二個i=2

因此,我的無包裝功能如下:

ff_1 <- function(x,mu=c(2,0.5),sd=c(0.2,0.3)){
      -sum(log(dnorm(x,mu[[1]],sd[[1]]))) 

    return(out)
    }

 ff_2 <- function(x,mu=c(2,0.5),sd=c(0.2,0.3)){
      -sum(log(dnorm(x,mu[[2]],sd[[2]]))) 

    return(out)
    }

然后,我需要為每個函數使用兩個不同的optim函數。

我搜索了許多網站和R幫助網站,但找不到該問題的解決方案。

有什么幫助嗎?

嘗試這一點,我想這只是將參數傳遞給優化的方法

# given data
set.seed(123)
x <- rnorm(10,2,0.5)

# use vector parOpt instead of specifying two; for convience
# with optim
ff <- function(x, parOpt){
  out  <- -sum(log(dnorm(x, parOpt[1], parOpt[2]))) 
  return(out)
}


# parameters in mu,sd vectors arranged in list
params <- list(set1 = c(2, 0.2), set2 = c(0.5, 0.3))

# output list
out <- list()

for(i in 1:2){
  # pass params (mu and sd) to optim, function ff and the data
  # note, since function ff has x argument, specify that in optim
  out[[i]] <- optim(par = params[[i]], fn=ff ,x=x)

}

應該給出這樣的東西:

[[1]]
[[1]]$par
[1] 2.0372546 0.4523918

[[1]]$value
[1] 6.257931

[[1]]$counts
function gradient 
      55       NA 

[[1]]$convergence
[1] 0

[[1]]$message
NULL


[[2]]
[[2]]$par
[1] 2.037165 0.452433

[[2]]$value
[1] 6.257932

[[2]]$counts
function gradient 
      73       NA 

[[2]]$convergence
[1] 0

[[2]]$message
NULL

希望這可以幫助。

或者,您可以使用fitdistrplus軟件包的命令fitdist找到相同的解決方案:

library(fitdistrplus)
set.seed(123)
x <- rnorm(10,2,0.5)
mu.start <- c(2,0.5)
sd.start <- c(0.2,0.3)
op <- vector("list",2)
for(i in 1:2){
  op[[i]] <- fitdist(x,"norm", start=c(mu.start[i],sd.start[i]))
}
op

結果是:

[[1]]
Fitting of the distribution ' norm ' by maximum likelihood 
Parameters:
   estimate Std. Error
1 2.0372546  0.1430588
2 0.4523918  0.1011464

[[2]]
Fitting of the distribution ' norm ' by maximum likelihood 
Parameters:
  estimate Std. Error
1 2.037165  0.1430719
2 0.452433  0.1011694

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM