2012-05-29 212 views
3

我已經搜索了這個,但徒勞無功。 問題是我有兩個列表,先用元件例如R:基於另一個列表重複列表的元素

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" 

預先感謝您的幫助

回答

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" 
+0

共同負擔:P –

相關問題