使用lapply时如何在列表下命名列表? [英] How to names lists under list when using lapply?

查看:88
本文介绍了使用lapply时如何在列表下命名列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个嵌套的循环,我想用lapply代替for循环来完成.我已经组成了以下简单示例:

I have a two nested loop which I want to do it with lapply instead of for loops. I have made up the following simple example:

a<-as.list(c(1,2))  
b<-as.list(c(6,7))  
results<-lapply(a, function(x) lapply(b, function(y) x+y))

> results  
[[1]]  
[[1]][[1]]  
[1] 7  

[[1]][[2]]  
[1] 8  


[[2]]  
[[2]][[1]]  
[1] 8

[[2]][[2]]  
[1] 9

如何为该列表分配名称,我可以使用names(result)< -a将名称分配给第一级,但是我不知道如何为第二级分配名称.命名应该循环执行,因为在我的主程序中b的长度可能会改变.我很高兴有人能给我一些提示.

how can I assign names to this list, I can assign names to the first level using names(result)<-a, but I do not know how to do it for the second level. And naming should be done in loop since in my main program length of b may change. I appreciate if any one can give me some hint.

推荐答案

您应注意, lapply()本身只是构造良好的 for()的包装循环,因此您不会获得任何效率,而只是获得可读性.除此之外,最简单的方法是将名称添加到嵌套的 lapply()调用中的列表中:

You should note that lapply() itself is just a wrapper for a well constructed for() loop, so you're not gaining any efficiency, just perhaps readability. That aside, the easiest approach is to add names to the lists going into your nested lapply() calls:

a<-as.list(c(1,2))
b<-as.list(c(6,7)) 
names(a) <- c("a","b")
names(b) <- c("c", "d")
results<-lapply(a, function(x) lapply(b, function(y) x+y))

此方法产生:

> results
$a
$a$c
[1] 7

$a$d
[1] 8


$b
$b$c
[1] 8

$b$d
[1] 9

您当然可以这样重命名嵌套的组件:

You can of course then rename nested components like this:

> names(results$a) <- c("e","f")
> results$a
$e
[1] 7

$f
[1] 8

这篇关于使用lapply时如何在列表下命名列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆