Search code examples
rmatrixvectorizationcurve-fittingnls

Vectorising building multiple models in R


I have data (a list with multiple matrix objects) that looks like this:

$matrix_1
    26/03/2012  02/04/2012  09/04/2012  16/04/2012  23/04/2012  30/04/2012  07/05/2012  14/05/2012  21/05/2012  28/05/2012
26/03/2012  500 40  30  20  21  18  8   7   8   5
02/04/2012  NA  100 25  19  16  15  10  6   7   8
09/04/2012  NA  NA  200 55  50  45  38  35  34  32
16/04/2012  NA  NA  NA  400 50  30  20  10  12  7

$matrix_b
    26/03/2012  02/04/2012  09/04/2012  16/04/2012  23/04/2012  30/04/2012  07/05/2012  14/05/2012  21/05/2012  28/05/2012
26/03/2012  500 40  30  20  21  18  8   7   8   5
02/04/2012  NA  100 25  19  16  15  10  6   7   8
09/04/2012  NA  NA  200 55  50  45  38  35  34  32
16/04/2012  NA  NA  NA  400 50  30  20  10  12  7

Right now I've written a loop to fit a curve to each row of my data using NLS with my own specified curve function. i.e. for matrix_a row 26/03/2012, I'm fitting a curve against these data points:

500 40  30  20  21  18  8   7   8   5

Within my loop I extract the curve coefficients to use later on

Is there a way I can vectorise this method? so that I don't have to use loops?

I use NLS in this way for each row:

fit.function <- function(a,x,b)
                   {return(a*x^b)}

 mod <- nls(values ~ fit.function(a,index_of_values,b))

where index_of_values is 1, 2, 3 etc.. (i.e. column number)


Solution

  • Thanks for helping, I ended up using sapply and it worked

    i.e. here are some snippets of my code:

    fit.function <- function(a,x,b)
                       {return(a*x^b)}
    
    
    xx<-sapply(setNames(1:10,rownames(dataset[1:10])), function(i) {
        to_predict= dataset[i,]
        ind = dataset2[i,]
        mod=nls(to_predict~ fit.function(a,ind,b))
        return(c(summary(mod)$coefficients[1],summary(mod)$coefficients[2]))
    })