我有以下清单:
lst = list(
cat = c("room","shower","garden"),
dog = c("street", "garden")
)我要得到的输出:
list(
list(
animal="cat",
place ="room"
),
list(
animal="cat",
place ="shower"
),
list(
animal="cat",
place ="garden"
),
list(
animal="dog",
place ="street"
),
list(
animal="dog",
place ="garden"
)
)目前,我使用以下代码:
library(plyr)
grasp <- function(animal, places)
{
llply(places, function(u) list(animal=animal, place=u))
}
Reduce(append, Map(grasp, names(lst), lst))但也许还有更优雅、更简洁、更新的东西吗?
发布于 2015-01-12 15:45:05
我不知道它是更优雅还是更简洁,我想它不是新的,但是,它仍然可以是另一种获得结果的方式:
unlist(lapply(names(lst),function(x){
lapply(lst[[x]],function(y,x){
list(animal=x,place=y)
},x=x)
}),recursive=F)我将我的解决方案和您的plyr方法列在一个列表中,列出了每个“动物”1000个“动物”和50个“位置”(我尝试了更多,但在我的计算机上花了太长时间.)下面是结果(我没有对magrittr方法进行基准测试,因为我的“虚拟”列表出现了错误):
base_meth<-function(){unlist(lapply(names(lst),function(x){lapply(lst[[x]],function(y,x){list(animal=x,place=y)},x=x)}),recursive=F)}
plyr_meth<-function(){Reduce(append, Map(grasp, names(lst), lst))}
microbenchmark(base_meth(),plyr_meth(),unit="relative",times=500)
# Unit: relative
# expr min lq mean median uq max neval cld
# base_meth() 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 500 a
# plyr_meth() 6.885256 6.844418 5.798948 6.527788 5.475684 7.589215 500 b发布于 2014-12-19 16:26:25
这与expand.grid函数的功能非常接近;然而,这会返回一个data.frame (您可能会考虑使用它)。但是,您可以将其转换为data.frames的列表。
# library(magrittr)
do.call(`expand.grid`, c(lst,stringsAsFactors = FALSE)) %>% split(., 1:nrow(.))应该表现得像你想要的那样
https://stackoverflow.com/questions/27569752
复制相似问题