[R] Name assignment in for loop

David Winsemius dwinsemius at comcast.net
Thu Nov 1 22:30:01 CET 2012


On Nov 1, 2012, at 2:16 PM, nrm2010 wrote:

> 
> 
> 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 = "") <- (...)

Wrong. There is no `paste<-` function.
> assign(paste("modelb", i, sep = "")) <- (...)
And.. there is no `assign<-` function.
> assign(paste("modelb", i, sep - ""), put linear model here)
And here you are using dash instead of equals.

The syntax is:

assign(name, object)

> assign(paste("text", 1, sep="_"), 1)
> text1
Error: object 'text1' not found
> text_1
[1] 1



> They all generate the same error message.

I rather doubt that.
> 
> 
> 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.

Which means you are leaving it for the readers to develop an example and test it. Nuts to that!

You should not be doing this anyway. Learn to use lists to store you related obkcts. Then it is a simple matter of using the `names<-` function. Untested in the absence of a reproducible example:

list.items <- as.list(1,2,3)
list.items
names(list.items) <- letters[1:3]
list.items

-- 
David.

> 
> 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
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list