You are currently browsing the tag archive for the ‘loop’ tag.

Frequently I find myself having to write something like this in R:

for (nm in names(x)) {
    l <- x[[nm]]
    ss <- summary(l)  # produce nice table for writing

Here x is some list, where each element contains some fitted model. This always bugs me, since I cannot use lapply, or other fancy functions like *lply (from package plyr). The problem is that I need to keep the name of the list element, and all of functions mentioned, do not do that. So if I have a generic function:

fun <- function(l, nm) {
    l  <- x[[nm]]
    ss <- summary(l)

I cannot use it with lapply like this


since then I need to pass different nm for each list element.

With foreach however it is very easy to do:

foreach(l=x,nm=names(x)) %do% {
    ss <-  summary(l)

Or I can use my super-convenient function:

foreach(l=x,nm=names(x)) %do% fun(l,nm)

You can even do some interesting stuff with parallelization, since foreach supports it. So if your computer has processor with several cores you can use both for intensive calculations. BTW if anyone knows easy way of highlighting R code in wordpress, let me know.