I'd like to know how I can iterate over a key/value pair from a list object in R, like the example below:
我想知道如何迭代R中列表对象的键/值对,如下例所示:
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?
有没有办法避免for循环(使用lapply()或类似)。会更快吗?
Thanks!
谢谢!
2 个解决方案
#1
12
The best solution of all is to simply call paste
directly without a loop (it's vectorized already):
最好的解决方案就是直接调用paste而不需要循环(它已经向量化了):
> 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:
之前在R-Help上提出的一个类似问题,有几个创意解决方案。 lapply无法显示函数内的名称。这个功能是由Romain Francois根据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"
#2
6
This should do it for you:
这应该为你做:
do.call(paste, list(toto, names(toto) ))
#1
12
The best solution of all is to simply call paste
directly without a loop (it's vectorized already):
最好的解决方案就是直接调用paste而不需要循环(它已经向量化了):
> 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:
之前在R-Help上提出的一个类似问题,有几个创意解决方案。 lapply无法显示函数内的名称。这个功能是由Romain Francois根据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"
#2
6
This should do it for you:
这应该为你做:
do.call(paste, list(toto, names(toto) ))