簡體   English   中英

nls引導錯誤的長度必須為正

[英]nls boot error must have positive length

我通過nlsBoot()收到以下錯誤,知道什么地方出錯了嗎?

Error in apply(tabboot, 1, quantile, c(0.5, 0.025, 0.975)) : 
  dim(X) must have a positive length

set.seed(1)
x = 1:100
y = x^2+rnorm(100,50,500)
plot(x,y)
d = data.frame(x =x, y=y)
mymodel = nls(y~x^b,start= list(b=1),data = d)
mymodel
library(nlstools)
nlsBoot(mymodel, niter = 999)

嘗試在應用nls函數之前定義公式,如下所示:

formula <- as.formula(y ~ x^b)
mymodel <-  nls(formula,start= list(b=1),data = d)

添加

好吧,我已經修改了代碼,現在它可以處理一個參數擬合。

# My suggestion is to erase all the environment first:
rm(list = ls())
# Then we start again:
set.seed(1)
x = 1:100
y = x^2+rnorm(100,50,500)
plot(x,y)
d = data.frame(x =x, y=y)
mymodel = nls(y~x^b,start= list(b=1),data = d)

這是您必須使用的功能:

nlsboot_onepar <- function (nls, niter = 999) 
{
if (!inherits(nls, "nls")) 
stop("Use only with 'nls' objects")
data2 <- eval(nls$data, sys.frame(0))
fitted1 <- fitted(nls)
resid1 <- resid(nls)
var1 <- all.vars(formula(nls)[[2]])
l1 <- lapply(1:niter, function(i) {
data2[, var1] <- fitted1 + sample(scale(resid1, scale = FALSE), 
                                  replace = TRUE)
nls2 <- try(update(nls, start = as.list(coef(nls)), 
                   data = data2), silent = TRUE)
if (inherits(nls2, "nls")) 
  return(list(coef = coef(nls2), rse = summary(nls2)$sigma))
})
if (sum(sapply(l1, is.null)) > niter/2) 
stop(paste("Procedure aborted: the fit only converged in", 
           round(sum(sapply(l1, is.null))/niter), "% during bootstrapping"))
tabboot <- sapply(l1[!sapply(l1, is.null)], function(z) z$coef,simplify = 
FALSE)
tabboot <- as.matrix(t(as.numeric(tabboot)))
rownames(tabboot) <- "b"
rseboot <- sapply(l1[!sapply(l1, is.null)], function(z) z$rse)
recapboot <- t(apply(tabboot, 1, quantile, c(0.5, 0.025, 
                                           0.975)))
colnames(recapboot) <- c("Median", "2.5%", "97.5%")
estiboot <- t(apply(tabboot, 1, function(z) c(mean(z), sd(z))))
colnames(estiboot) <- c("Estimate", "Std. error")
serr <- sum(sapply(l1, is.null))
if (serr > 0) 
warning(paste("The fit did not converge", serr, "times during 
bootstrapping"))
listboot <- list(coefboot = t(tabboot), rse = rseboot, bootCI = recapboot, 
               estiboot = estiboot)
class(listboot) <- "nlsBoot"
return(listboot)
}

然后我們使用它:

result <- nlsboot_onepar(mymodel, niter = 999)

如果要繪制參數分布,可以執行以下操作:

graphics.off()
plot(density(as.vector(result$coefboot)))
# or
hist(as.vector(result$coefboot))

希望對您有所幫助。

暫無
暫無

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

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