R:基于另一个列表重复列表的元素

时间:2012-05-29 17:03:02

标签: r list repeat

我搜索过这个但是徒劳无功。 问题是我有两个列表,首先是要重复的元素 例如

my.list<-list(c('a','b','c','d'), c('g','h'))

,第二个列表是每个元素重复的次数

repeat.list<-list(c(5,7,6,1), c(2,3))

我想创建一个新列表,其中my.list中的每个元素都基于repeat.list重复 即 结果:

[[1]]
[1] "a" "a" "a" "a" "a" "b" "b"  "b" "b" "b" "b" "b" "c" "c" "c" "c" "c" "c" "d" 
[[2]]
[1] "g" "g" "h" "h" "h" 

提前感谢您的帮助

1 个答案:

答案 0 :(得分:6)

使用mapply

mapply(rep, my.list, repeat.list)
[[1]]
 [1] "a" "a" "a" "a" "a" "b" "b" "b" "b" "b" "b" "b" "c" "c" "c" "c" "c" "c" "d"

[[2]]
[1] "g" "g" "h" "h" "h"

lapply也有诀窍,但更详细:

lapply(seq_along(my.list), function(i)rep(my.list[[i]], repeat.list[[i]]))
[[1]]
 [1] "a" "a" "a" "a" "a" "b" "b" "b" "b" "b" "b" "b" "c" "c" "c" "c" "c" "c" "d"

[[2]]
[1] "g" "g" "h" "h" "h"