R: create a vector based on a list

Viewed 59

I have the following list called m1:

> m1
[[1]]
[1] 36 37 38

[[2]]
[1] 34 35

[[3]]
[1] 30 31 32 33

[[4]]
[1] 24 25 26 27 28 29

[[5]]
[1] 20 21 22 23

[[6]]
[1] 14 15 16 17 18 19

[[7]]
[1] 11 12 13

[[8]]
[1]  7  8  9 10

[[9]]
[1] 5 6

[[10]]
[1] 1 2 3 4

[[11]]
integer(0)

I would like to create a vector based on this list, which has the value 1 at positions 36, 37, and 38; the value 2 at positions 34 and 35, etc. The final output should be:

vector_1 <- c(10, 10, 10, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 1, 1, 1)

How can I accomplish this in R?

EDIT:

Thanks to a comment below:

> rep(length(m1):1, sapply(m1, length))
 [1] 11 11 11 10 10  9  9  9  9  8  8  8  8  8  8  7  7  7  7  6  6  6  6  6  6  5  5  5  4
[30]  4  4  4  3  3  2  2  2  2

That doesn't quite give me what I want, but it's definitely on the right track!

4 Answers
Related