How to names lists under list when using lapply?

故事扮演 提交于 2021-01-27 21:57:42

问题


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

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.


回答1:


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))

This approach yields:

> 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


来源:https://stackoverflow.com/questions/31349331/how-to-names-lists-under-list-when-using-lapply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!