Search code examples
rregressionnls

How to add noise in R


I'm new in R programming. I have a quation and using the nls fucntion of R to estimate some parameters (b1, b2, b3, b4, b5, b6, b7). I have my starting values but somehow I get "singular gradient" error from R. When I chane one or two of my starting values, It works fine. But My starting values should not be changed due to my research paper. I do some research on the web and found out that this situation is originated from the lack of noise. Here is my work code. Does anyboy know how to add noise to this code? Thanks.

    ComputeDi.Bi <- function(hi, d, h, b1, b2, b3, b4, b5, b6, b7){

            q <- hi/h
            t <- 1.30/h
            A <- sin(q*3.14/2)
            C <- sin(t*3.14/2)
            B <- log(A)/log(C)

            di <- d * (B^(b1+b2*sin(3.14*q/2)+b3*cos(3*3.14*q/2)+b4*sin(3.14*q/2)/q+b5*d+b6*q*(d^0.5)+b7*q*(h^0.5)))
            return(di)
    }

setwd("../Data")
sylvestris <- read.csv("ScotsPine100Trees_Turkey.csv")



nlmod.fp.di <- nls(di ~ ComputeDi.Bi(hi, d, h, b1, b2, b3, b4, b5, b6, b7), data = sylvestris, start = c(b1 = 2.16, b2 = -0.070, b3 = 0.031, b4 = -0.95, b5 = 0.0001, b6 = 0.075, b7 = -0.08), control = nls.control(tol = 1e-07))
summary(nlmod.fp.di, correlation = T)                            

Solution

  • rnorm will give you noise from a normal distribution. For example:

    ComputeDi.Bi(hi, d, h, b1, b2, b3, b4, b5, b6, b7) + rnorm(length(hi), mean = 0, sd = 0.1)

    runif, rpois, rbinom and many more are also available.

    I'm not sure that's what you want to do here though... I'm maybe not understanding your question but if you don't already have noise then there is no need to fit a statistical model.