Possible Package conflicts with minpack.lm for nlsLM optimization
It's both It's both of the masked functions that cause the problem. However, you an call still call tidyverse
. (ggplot2
and dplyr
are already called, when you call tidyverse
, so calling them again isn't necessary.) To change the two masked functions back, keep your code working, while still using tidyverse
, add this to the code: filter <- stats::filter
and lag <- stats::lag
and it will work. However, if you want to use the dplyr
version of these calls, you can either change them back or append the library to the function.
library(tidyverse)
library(minpack.lm)
# change back the only two masked functions
filter <- stats::filter
lag <- stats::lag
From here, call in your data object df1
and the rest of your functions as you had originally called them.
# objects & df used in ans.2 function:
h <- 552
mp <- 77
R_ <- 0.00831
K <- 273.15
gstart <- data.frame(h = c(550)) # mp=c(70,80), h=c(500,600), mp=c(77)
# exponential function for finding v in df1:
ans.2<- function(x){
h * ((1/ (1 + exp((h/ R_)*((1/ (x + K)) - (1/(mp + K))))))
-(1/ (1 + exp((h/ R_)*((1/ (lag(x) + K)) - (1/(mp + K))))))
/((x - lag(x)) + K))
}
ans.2(x = df1$t) # checking if function works
# finding values of h and mp, minimize residual sum of squares (RSS) between C and v:
# non-expanded ans.2
nlsLM(formula = C~ ans.2(x = df1$t),
data = df1,
start = list(h = 550,
mp = 77),
trace = T)
#nlsLM test:
nlsLM(formula = C ~ h*((
(1/ (1 + exp((h / R_)*((1/(t + K))-(1/(mp + K))))))
-(1/ (1 + exp((h / R_)*((1/(lag(t)+ K))-(1/(mp + K))))))
) /((t - lag(t)) + K)), data = df1, start = gstart, trace = T)
# saving nlsLM outputs
nls_1 <- summary(nlsLM(formula= C~ h * (
((1/(1 + exp((h/ R_)*((1/ (t + K))-(1/ (mp + K))))))
-(1/ (1 + exp((h/ R_) * ((1/ (lag(t) + K))-(1/ (mp + K))))))
/((t - lag(t)) + K))),
data = df1,
start = list(h = 50), #,mp=77
trace = F))
You will get an error:
Error in nlsModel(formula, mf, start, wts) :
singular gradient matrix at initial parameter estimates
This is the model outcome that I found.
# Formula: C ~ h * (((1/(1 + exp((h/R_) * ((1/(t + K)) - (1/(mp + K)))))) -
# (1/(1 + exp((h/R_) * ((1/(lag(t) + K)) - (1/(mp + K))))))/((t -
# lag(t)) + K)))
#
# Parameters:
# Estimate Std. Error t value Pr(>|t|)
# h 333.59 45.07 7.401 1.97e-11 ***
# ---
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
# Residual standard error: 0.2153 on 121 degrees of freedom
#
# Number of iterations to convergence: 10
# Achieved convergence tolerance: 1.49e-08
#