Home > OS >  How to store a grouped loop object by categorical variable in R
How to store a grouped loop object by categorical variable in R

Time:11-26

The title might sound confusing but the idea is to create a group of population parameter data of Channel Darters fish (FSAdata) from two locations using loop in R. This following code is working

require(FSA)
require(FSAdata)
require(car)

data("DarterOnt")
str(DarterOnt)

location <- unique(DarterOnt$river)

vb <- vbFuns(param = "Typical")

for (i in 1:length(location)) {
  dat <- filter(DarterOnt, river == location[i])

f.starts <- vbStarts(tl ~ age, data = dat)
f.fit[[i]] <- nls(tl ~ vb(age, Linf, K, t0), data = dat, start = f.starts)

}

f.fit[[1]]

However, I should run f.fit <- nls(tl ~ vb(age, Linf, K, t0), data = dat, start = f.starts) first, without [[i]] separately (after previously run the "failed code"), and then re-run the above code in order for the loop to work fine. If not, there will be a warning Error: object 'f.fit' not found. I am not too familiar with loop in R, but what cause this problem? is there any workaround?

CodePudding user response:

Objects need to be initialized before you can assign to a specific index of them.

To initialize the f.fit object, right before the loop starts put f.fit <- list() to create it as an empty list - then you will be able to assign to it in the loop just as you have it

  • Related