I'm trying to code a non-linear regression in R to fit data I have regarding the relationship between temperatures and types of precipitations.
I first created 2 vectors with my data:
vec_temp_num
[1] -8.5 -8.0 -6.5 -6.1 -5.9 -5.8 -5.6 -5.4 -5.3 -5.1 -4.9 -4.8 -4.7 -4.5 -4.3 -4.2 -4.1
[18] -4.0 -3.9 -3.8 -3.7 -3.6 -3.5 -3.4 -3.3 -3.2 -3.1 -3.0 -2.9 -2.8 -2.6 -2.5 -2.4 -2.3
vec_rain
[1] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[9] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 1.00000000 0.00000000 0.00000000
[17] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[25] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.33333333 0.00000000 0.00000000
vec_temp_num contains a list of temperatures and vec_rain has for each of them a percentage by type of precipitation observed, basically rain or snow (I chose to start with one of them to simplify the process). Both vectors contain 300 lines and are "as.numeric".
The function is the following:
func_rain <- function(x,b){(1/(1+exp(-b*x)))}
I then tested my function and got a plot that looks like it should be, so until this step everything seems to be ok.
But when I try to write the nls formula:
Rain_fit<-nls(vec_rain~func_rain(vec_temp_num,b), start=c(vec_temp_num=2.6, b=1))
I get a error message saying:
Error in qr(.swts * gr) : dims [product 2] do not match the length of object [300]
It seems that I should have my data as a matrix opposed to a vector (which I don't get because some forums advise to create vectors) but then I tried to directly use data from my data frame (df = dp.w2/rain & temperature columns):
Rain_fit<-
nls(dp.w2$rain~func_rain(dp.w2$temperature,b),start=list(temperature=2.6,rain=1,
b=1))
and got another error message:
Error in parse(text = x, keep.source = FALSE) : :2:0: unexpected end of input 1: ~ ^
I've read a lot of question/answers about the nls function but it's been some days now and I just can't find the right way to fit my data so thanks a lot in advance for your help!
PS: I'm a total beginner so if you could provide a "step by step" or detailed (for dummies) answer it would be awesome!