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!
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With