I am trying to fit a discrete function to my dataset using nls(). fit<-nls(T2~form(SOA,t1weight,t2weight,d1weight), start=list(t1weight=1,t2weight=1,d1weight=1), data=data1, trace=TRUE) The problem is that my function ("form") includes a discrete function and in that function I used the variable SOA to define the discrete function (see below). form<-function(SOA,t1weight,t2weight,d1weight){ decay_functionT1_1 <- 0 decay_functionT1_2 <- rep(t1weight,ttime) decay_functionT1_3 <- t1weight*exp(-x/q) decay_functionT1_3[decay_functionT1_3<threshold]<- 0 T1 <- c(decay_functionT1_1, decay_functionT1_2, decay_functionT1_3) decay_functionT2_1 <- rep(0,SOA) decay_functionT2_2 <- rep (1,ttime) decay_functionT2_3 <- decay_t2(x1) decay_functionT2_3[decay_functionT2_3<threshold]<- 0 T2 <- c(decay_functionT2_1, decay_functionT2_2, decay_functionT2_3) When I call nls() with my function a get an error message: Error in rep(0, SOA) : invalid 'times' argument That is propably due to the way nls() calls my function with the variable SOA. Can you help me to fix that?