[R] Name assignment in for loop

nrm2010 nrm2010 at zoho.com
Thu Nov 1 22:16:11 CET 2012



Dear helpeRs-

I'm using a for loop to create a series of models.  
I'm trying to assign a name to each model created, 
using the loop index.  The loop gets stuck at the name
 of the model, giving the error "target of assignment 
expands to non-language object".  The linear model runs 
without error; only the name is problematic.

Here is the current loop syntax.  The use of dat and dat2
is not an error.  I'm pulling data from 2 sources for the model.

for (i in 1:dim(dat2)[[1]]) { 
assign("modelb",i) <- lm(log(dat$flux) ~ dat$Tsoil_flux, 
subset = dat$chamber == dat2$chamber[i] & dat$year == dat2$year[i] & dat$doy >= dat2$day1[i] & dat$doy <= dat2$day2[i])
dat2$coef[i] <- coef(assign("modelb",i, sep = ""))[[2]]
dat2$Rsq[i] <- summary(assign("modelb",i, sep = ""))[[9]]
}

I have also tried
assign("modelb",1:i) #following the ?assign example
paste("modelb", i, sep = "") <- (...)
assign(paste("modelb", i, sep = "")) <- (...)
assign(paste("modelb", i, sep - ""), put linear model here)
They all generate the same error message.


dim(dat2)[[1]] is 29
> dim(dat2)[[1]]
[1] 29

> class(dim(dat2)[[1]])
[1] "integer"

I have not included data because the problem is with the naming syntax;
 no data are involved except for the number 29.

Given this approach, rather than the sapply() approach, what is the correct
 syntax for naming each model in the sequence?

Thank you in advance.

Toby Gass



More information about the R-help mailing list