簡體   English   中英

在R公式中使用函數

[英]Use a function in R formula

任何幫助,將不勝感激。 我正在優化對數正態分布的參數,以使估計比例與一組目標值(距離)匹配。 使用以下函數計算比例:

adj_sumifs <- function(sum_array, condition_array, f, m=1){
n <- length(condition_array)
sm = 0
if (n == length(condition_array)){
  fun <- function(x,i){if (f (condition_array[i])){sum_array[i] + x}else{x} }
  sm <- Reduce(fun,1:n,0)
} 
ifelse(m <= 0, sm , sm/m)

}

estimate.inrange <- function(vals,dist,lower,upper,total){
  n <- length(lower)
  if (n == length(upper)){
    sapply(1:n, function(i){ ifelse(i < n ,
                                adj_sumifs(vals,dist, (function(x) x >= lower[i] && x < upper[i]),total) ,
                                adj_sumifs(vals,dist, (function(x) x >= lower[i]) , total)
                             ) }
          )
  }else{
    # for a failure in the process
    as.numeric()
  }
}

我想優化的功能是:

calculate_Det_ptns <- function(alpha, beta, pxa, low,up, distances, eF){
  temp <- numeric()
  if ( length(pxa) == length(distances) && length(low) == length(up) )
  {
    ln_values <- as.numeric(Map(function(pa,d) eF * pa * dlnorm(d, meanlog = alpha, sdlog = beta),pxa,distances))
    temp <- estimate.inrange (ln_values,distances,low,up, total = sum(ln_values))
  }
  temp
}

使用Levenberg-Marquardt算法進行優化

lnVals <- nlsLM(target  ~ calculate_Det_ptns(alpha = a,beta = b, pxa = odab,low = low, up = up, distances = dist, eF = expF),
                          start = list(a = mu, b = sd ), 
                          trace = T) 

從相同的數據文件中提取上,下和目標,例如

low, up, target
1,2,0.1
2,3,0.4
3,4,0.6
4,5,0.6
5,6,0.9

odabdistance是任意長度的向量(通常比目標長得多,等等)。 當目標文件有150行,並且distancesodab具有大約500000值時,該過程運行良好。 但是,由於我無法理解的原因,當目標文件具有約16行時,is失敗。 錯誤消息是:

Error in model.frame.default(formula = ~target + odab + low + up + dist) : 
  variable lengths differ (found for 'odab')

這表明該函數未在公式中求值。 誰能提出解決方案或解釋? 重要的是要重新估計每個新畝和標准房的比例。

您可以嘗試用I()包圍該函數,該函數將在評估公式之前按原樣對其進行評估; 但是,由於我缺少某些引用的對象(a,b,odab,dist,expF,mu,sd),因此我無法使用提供的代碼來復制您的問題,因此我無法確認這是否可行。 nVals <- nlsLM(target ~ I(calculate_Det_ptns(alpha = a,beta = b, pxa = odab,low = low, up = up, distances = dist, eF = expF)), start = list(a = mu, b = sd ), trace = T)

暫無
暫無

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

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