Search code examples
rdynamicnested-loopspasteassign

Use of Assign/Paste in R to dynamically name in R


When I use a non dynamic name things works as expected:

summary(date1fit <- lm(masterdf.date[[1]]$LeastDiluteMPN~masterdf.date[[1]]$temp))

When I try to name the fit based on the [[i]] however I get errors stating "could not find function 'paste<-' " or " could not find function 'assign<-' ". I have tried the following:

summary(date.names[[i]] <- lm(masterdf.date[[1]]$LeastDiluteMPN~masterdf.date[[1]]$temp))
summary(paste(date.names[[i]]) <- lm(masterdf.date[[1]]$LeastDiluteMPN~masterdf.date[[1]]$temp))
summary(assign(date.names[[i]]) <- lm(masterdf.date[[1]]$LeastDiluteMPN~masterdf.date[[1]]$temp))
summary(assign(paste(date.names[[i]]), "", sep="")) <- lm(masterdf.date[[1]]$LeastDiluteMPN~masterdf.date[[1]]$temp))

Can anyone help me figure out where I'm going wrong here? What am I missing? Do I need nested loop? The full code I'm working with is below.

Thanks!

masterdf <- masterdf[order(as.Date(masterdf$date, format="%d/%m/%Y")),]

dates <- unique(masterdf$date)

masterdf.date <- list()
for(i in 1:length(dates))   {
masterdf.date[[i]] <- masterdf[masterdf$date==dates[i],]
                    }
date.names <- paste("date", dates, sep="")

summary(DYNAMIC NAME <- lm(masterdf.date[[1]]$LeastDiluteMPN~masterdf.date[[1]]$temp))

Solution

  • Why are you doing an assigment inside a summary? Ick. Do it in two steps:

    > d=data.frame(x=1:10, y=runif(10))
    > dmodel <- lm(y~x,data=d)
    > summary(dmodel)
    

    Then you can have a list and do:

    d=list()
    for(i in 1:10){
      d[[i]] = lm(....whatever...)
      summary(d[[i]])
    }
    

    If you are crazy enough to want to do "dynamic names", then:

     crazyname = paste("mad",i)
     assign(crazyname, lm(y~x,data=d))
     summary(get(crazyname))