You are currently browsing the tag archive for the ‘list’ 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
    write.csv(ss,file=paste(nm,".csv",sep=""))
}

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)
    write.csv(ss,file=paste(nm,".csv",sep=""))
}

I cannot use it with lapply like this

 lapply(x,fun)

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)
    write.csv(ss,file=paste(nm,".csv",sep=""))
}

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.

Naujausi komentarai

vzemlys apie Rožiniai akiniai
Audrius apie Rožiniai akiniai
Karl apie Time series data aggregation u…
Vytautas Astrauskas apie Matematinio teksto rinkimo tur…
Auksinis kardas apie Drawing national flags on maps…
2020 m. gegužės mėn.
Pr A T K Pn Š S
 123
45678910
11121314151617
18192021222324
25262728293031