user1424238
user1424238

Reputation: 41

R: repeat elements of a list based on another list

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

Upvotes: 4

Views: 3187

Answers (1)

Andrie
Andrie

Reputation: 179408

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"

Upvotes: 8

Related Questions