I am trying to perform a nls fit on multiple experiments (say exp1 and exp2).
When running the code on R 3.6 (or previous versions) it works nicely (for instance here: https://www.tutorialspoint.com/execute_r_online.php on 3.4.1). On R 4.0.2, I get an error:
Error in nls(donnees$ally ~ donnees$allx * a[donnees$allexp] + b[donnees$allexp], : Missing value or an infinity produced when evaluating the model
valx1<-c(1,2,3,4,5,6)
valx2<-c(2,7,8,9)
allx<-c(valx1,valx2)
valy1<-c(2,3,8,9,10,12)
valy2<-c(3,10,11,12)
ally<-c(valy1,valy2)
exp1<-rep('exp1',length(valx1))
exp2<-rep('exp2',length(valx2))
allexp<-c(exp1,exp2)
df<-data.frame(allx,ally,allexp)
fitexp<-nls(df$ally ~ df$allx*a[df$allexp]+b[df$allexp],start=list(a=c(1,1),b=c(1,1)))
summary(fitexp)
In R 4.0+ allexp
is character whereas it would have been factor in earlier versions of R. Convert it to a factor or numeric variable. We convert to a factor below. Also the data frame is normally written as a separate argument and not part of the formula.
df2 <- transform(df, allexp = factor(allexp))
nls(ally ~ allx * a[allexp] + b[allexp], df2,
start = list(a = c(1, 1),b = c(1, 1)))
Also note that nls
is not needed since the model is linear and lm
could have been used with the appropriate formula:
df3 <- within(df, {
b1 = +(allexp == "exp1")
b2 = +(allexp == "exp2")
a1 = allx * b1
a2 = allx * b2
})
lm(ally ~ a1 + a2 + b1 + b2 + 0, df3)