[R] Idiomatic looping over list name, value pairs in R

Duncan Murdoch murdoch.duncan at gmail.com
Tue May 4 16:38:40 CEST 2010


On 04/05/2010 10:24 AM, Luis N wrote:
> Considering the python code:
>
> for k, v in d.items(): do_something(k); do_something_else(v)
>
> I have the following for R:
>
> for (i in c(1:length(d))) { do_something(names(d[i]));
> do_something_else(d[[i]]) }
>
> This does not seem seems idiomatic. What is the best way of doing the
> same with R?
>   

You could do it as

for (name in names(d)) {
  do_something(name)
  do_something(d[[name]])
}

or

sapply(names(d), function(name) {
   do_something(name)
   do_something_else(d[[name]])
})

or

do_both <- function(name) {
  do_something(name)
  do_something_else(d[[name]])
}
sapply(names(d), do_both)

My choice would be the first version, but yours might differ.

Duncan Murdoch



More information about the R-help mailing list