R: repeat elements of a list based on another list

亡梦爱人 提交于 2019-12-10 19:03:04

问题


I have searched for this but in vain. the problem is I have two lists, first with the elements to be repeated for example

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

and the second list is the number of times each element is to be repeated

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

I would like to create a new list in which each element in my.list is repeated based in repeat.list i.e. result:

[[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" 

Thank you in advance for your help


回答1:


Use 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 also does the trick, but is more verbose:

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"


来源:https://stackoverflow.com/questions/10803585/r-repeat-elements-of-a-list-based-on-another-list

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