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"