4

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

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" 

预先感谢您的帮助

4

1 回答 1

8

使用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"
于 2012-05-29T17:09:29.173 回答