I have several nonlinear regression models (nls) saved as a1, a2,..., a_n. I would like to get a vector of related determinantion coefficients.
E.g.
y <- c(1.0385, 1.0195, 1.0176)
x <- c(3,4,5)
data <- data.frame(x,y)
b1 <- function(x,a,b) {a/b^x}
b2 <- function(x,a,b) {a^b^x}
a1 <- nls(y ~ b1(x,a,b), data = data, start = c(a=0.9, b=0.6))
a2 <- nls(y ~ b2(x,a,b), data = data, start = c(a=0.9, b=0.6))
I can get both coefficients of detetermination using
a <- sum(residuals(a1)^2)
b <- sum((y - mean(y))^2)
1 - (a/b)
#[1] 0.8198396
a <- sum(residuals(a2)^2)
b <- sum((y - mean(y))^2)
1 - (a/b)
#[1] 0.9066859
but what if I have let say 20 models?
I tried to use a cycle for
, which didn't work for me as the class is nls, neither a vector nor a matrix.
Use a list
of all your results and then apply a function to it:
results <- list(a1,a2)
b <- sum((y - mean(y))^2)
1 - (sapply(results,function(x) sum(residuals(x)^2) ) / b )
#[1] 0.8198396 0.9066859