I am VERY new to loops. Some of my loops have been successful, others... not so much.
I have some observed data (df_obs) that I'd like to test against my model predictions (df_pred).
MY CURRENT AIM: write a loop which makes a list of data frames, so that can I use this list in future loops assessing model performance. I will probably be back for help with THOSE loops...
YES: I do want a list of data frames. I'm working with 50+ species and have a bunch of tests to run on these values.
MAYBE: I think I want a for() loop, but if a different method is easier e.g. lapply(), I'm open to suggestions.
I've done my best to create a reproducible data set and code that mimics what I am working with:
#observed presence (1) and absence (0)
set.seed(733)
df_obs <- data.frame(plot = 1:10,
sp1 = sample(0:1, 10, replace = TRUE),
sp2 = sample(0:1, 10, replace = TRUE),
sp3 = sample(0:1, 10, replace = TRUE))
#predicted probability of occurrence (ranges from 0 to 1)
set.seed(733)
df_preds <- data.frame(plot = 1:10,
sp1 = runif(10, 0, 1),
sp2 = runif(10, 0, 1),
sp3 = runif(10, 0, 1))
sppcodes <- c("sp1", "sp2", "sp3")
test.eval.list <- vector("list", length = length(sppcodes))
names(test.eval.list) <- sppcodes
for(i in seq_along(sppcodes)){
sppn <- sppcodes[i]
plot = df_obs$plot
obs = df_obs[,sppn]
pred = df_preds[,sppn]
df <- data.frame(plot, obs, pred) #produces dataframe as expected
test.eval.list[sppn] <- df #problem seems to be here, it ends up assigning a vector of numbers...
}
Could someone please help me understand why I am not ending up with a list of data frames, and give a correct way of doing so?
Please note - I know there are areas which could be done in a single line of code, I prefer this way of spreading the code out to understand which parts are/are not working.