Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over key/value pair from a list()

Tags:

I'd like to know how I can iterate over a key/value pair from a list object in R, like the example below:

toto <- list(a="my name is",b="I'm called",c="name:") myfun <- function(key,value) paste(value,key) for( key in names(toto) ) toto[key] <- myfun(key,toto[[key]]) 

Is there a way to avoid the for loop (using lapply() or such). Would it be faster?

Thanks!

like image 841
caas Avatar asked Dec 21 '10 14:12

caas


People also ask

How do you iterate through a list with key-value pairs in Python?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.

How do you iterate over a dictionary key?

In order to iterate over the values of the dictionary, you simply need to call values() method that returns a new view containing dictionary's values.


1 Answers

The best solution of all is to simply call paste directly without a loop (it's vectorized already):

> paste(toto, names(toto)) [1] "my name is a" "I'm called b" "name: c"   

A similar question previously asked on R-Help, with several creative solutions. lapply cannot show the names within the function. This function was provided by Romain Francois based on something by Thomas Lumley:

yapply <- function(X,FUN, ...) {    index <- seq(length.out=length(X))    namesX <- names(X)    if(is.null(namesX))      namesX <- rep(NA,length(X))    FUN <- match.fun(FUN)    fnames <- names(formals(FUN))    if( ! "INDEX" %in% fnames ){      formals(FUN) <- append( formals(FUN), alist(INDEX=) )      }    if( ! "NAMES" %in% fnames ){      formals(FUN) <- append( formals(FUN), alist(NAMES=) )      }    mapply(FUN,X,INDEX=index, NAMES=namesX,MoreArgs=list(...))  } 

Here's an example of usage:

> yapply(toto, function( x ) paste(x, NAMES) )              a              b              c  "my name is a" "I'm called b"      "name: c"  
like image 185
Shane Avatar answered Nov 24 '22 10:11

Shane