In R, how do I use stub to create names (of data frames, variables & plots) in a loop? -
i'm working set of results of inla
package in r. these results stored in objects meaningful names can have, instance, model_a
, model_b
... in current environment. each of these models i'd several processing tasks including extracting of data separate data frame, can used merge spatial data create map, etc.
turning simpler, reproducible example let's assume 2 results
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) group <- gl(2, 10, 20, labels = c("ctl","trt")) weight <- c(ctl, trt) model_a <- lm(weight ~ group) model_b <- lm(weight ~ group - 1)
i can handle steps individual model, instance:
model_a_sum <- data.frame(var = character(1), model_a_value = numeric(1)) model_a_sum$var <- "intercept" model_a_sum$model_a_value <- model_a$coefficients[1] png("model_a_plot.png") plot(model_a, las = 1) dev.off()
now, i'd reuse code each of models, constructing correct names depending on model i'm using. i'm more stata r person , inside stata trivial task use stub of name (model_a
, or a
only..) , construct foreach
loop implement steps, adapting names each of models.
in r, loops have been bashed on internet presume shouldn't attempt venture territory of:
models <- c("model_a", "model_b", "model_c") (model in models) { ... }
what better solution such scenario?
update 1: since comments suggested for
might indeed option i'm trying put tasks loop. far manged name data frame correctly using assign
, correct data plotted under correct name using get
:
models <- c("model_a", "model_b") (i in 1:length(models)) { # create df name.df <- paste0(models[i], "_sum") assign(name.df, data.frame(var = character(1), value = numeric(1))) # replace variables of df results model # plot , save name.plot <- paste0(models[i], "_plot.png") png(name.plot) plot(get(models[i]), = 1, las = 1) dev.off() }
is reasonable approach? better solutions?
one thing cannot solve having second variable of df named according model (ie. model_a_value
instead of current value
. ideas how solve that?
some general tips/advice:
as mentioned in comments, don't believe of negativity
for
loops in r. issue not bad, more correlated bad code patterns inefficient.more important use right data organization. don't keep models each in separate object!. put them in list:
l <- vector("list",3) l[[1]] <- lm(...) l[[2]] <- lm(...) l[[3]] <- lm(...)
then name list:
names(l) <- paste0("model_",letters[1:3])
now can loop on list without resorting awkward , unnecessary tools assign
, get
, , more importantly when you're ready step for
loops tools lapply
you're go.
i use similar strategies data frames well.
Comments
Post a Comment