Skip to content

simplify source code

4 messages · Dennis Murphy, Christof Kluß, R. Michael Weylandt

#
Hi

I would like to shorten

mod1 <- nls(ColName2 ~ ColName1, data = table, ...)
mod2 <- nls(ColName3 ~ ColName1, data = table, ...)
mod3 <- nls(ColName4 ~ ColName1, data = table, ...)
...

is there something like

cols = c(ColName2,ColName3,ColName4,...)

for i in ...
   mod[i-1] <- nls(ColName[i] ~ ColName1, data = table, ...)

I am looking forward to help

Christof
#
Hi:

Here's one way you could do it. I manufactured some fake data with a
simple model to illustrate. This assumes you are using the same model
formula with the same starting values and remaining arguments for each
response.

dg <- data.frame(x = 1:10, y1 = sort(abs(rnorm(10))),
                  y2 = sort(abs(rnorm(10))), y3 = sort(abs(rnorm(10))))

# Model: y = b0 + b1 exp(x/theta)
vars <- c('y1', 'y2', 'y3')

# Function to create the model formula by plugging in the
# response y and run the model
mfun <- function(y) {
     form <- as.formula(paste(y, 'cbind(1, exp(x/th))', sep = ' ~ '))
     nls(form, data = dg, start = list(th = 0.3), algorithm = 'plinear')
    }

# Generate a list of model objects:
mlist <- lapply(vars, mfun)

# To see what they contain:
str(mlist[[1]])
str(summary(mlist[[1]]))

# Extract a few features from each:
# The first two return matrices, the third returns a list

do.call(rbind, lapply(mlist, function(m) coef(m)))
do.call(rbind, lapply(mlist, function(m) deviance(m)))
lapply(mlist, function(m) summary(m)$cov.unscaled)


To get more control over the output format, the plyr package can come
in handy. For example, to get data frames for the first two
extractions above, one would do

library('plyr')
ldply(mlist, function(m) coef(m))
ldply(mlist, function(m) deviance(m))

# ldply() means list input, data frame output (ld).
# For the third extraction, one has a list input and a list output:
llply(mlist, function(m) summary(m)$cov.unscaled)

HTH,
Dennis
On Sat, Nov 26, 2011 at 2:30 PM, Christof Klu? <ckluss at email.uni-kiel.de> wrote:
2 days later
#
Hi Dennis,

thank you very much. That works fine.

Is there a possibility that R continue even if one of the models is not 
solvable? R currently terminates with an error message.

greetings
Christof


Am 27-11-2011 01:34, schrieb Dennis Murphy:
#
Look into tryCatch() for error handling.

Michael
On Tue, Nov 29, 2011 at 7:01 AM, Christof Klu? <ckluss at email.uni-kiel.de> wrote: