## adding repeating pattern while converting list to matrix in R

Question

I am looking for a fast way to convert a list into a matrix with an additional column containing a repeating `1:5` pattern. For instance, the list `mat` looks like this. The list and the repeating pattern can get to thousands of values in length and so a fast approach would be ideal.

I can convert the list to a matrix using `melt` (may not be ideal for large matrices though), however, I am having trouble getting the repeating pattern to work.

The matrix looks like this

``````mat

[[1]]
[1] 5

[[2]]
[1] 1 4 5

[[3]]
[1] 3 1

[[4]]
[1] 4 6 5 3
``````

The output should contain the values of the list as well as an index column containing a `1:5` repeating pattern depending on the length of each index in the list. For instance, `mat[[4]]` contains 4 values, therefore the index column should contain a values `1:4`

``````output

[,1] [,2]
5  1
1  1
4  2
5  3
3  1
1  2
4  1
6  2
5  3
3  4
``````

Show source

## Answers to adding repeating pattern while converting list to matrix in R ( 2 )

1. ``````mat <- list(5, c(1,4,5), c(3,1), c(4,6,5,3))  ## your example data
``````

We can use basic operations:

``````cbind( unlist(mat), sequence(lengths(mat)) )

#      [,1] [,2]
# [1,]    5    1
# [2,]    1    1
# [3,]    4    2
# [4,]    5    3
# [5,]    3    1
# [6,]    1    2
# [7,]    4    1
# [8,]    6    2
# [9,]    5    3
#[10,]    3    4
``````

Alternatively,

``````cbind( unlist(mat), unlist(lapply(mat, seq_along)) )
``````
2. Here is another option with `Map`. We get the `sequence` of each `list` element with `lapply`, `cbind` the corresponding elements of `list` using `Map` and `rbind` it.

``````do.call(rbind, Map(cbind, mat, lapply(mat, seq_along)))
#     [,1] [,2]
#[1,]    5    1
#[2,]    1    1
#[3,]    4    2
#[4,]    5    3
#[5,]    3    1
#[6,]    1    2
#[7,]    4    1
#[8,]    6    2
#[9,]    5    3
#[10,]   3    4
``````

Or with `data.table`, we `melt` the `list` to a 2 column `data.frame`, convert it to `data.table` with `setDT` and assign (`:=`) the sequence of 'L1' to 'L1' after grouping by 'L1'

``````library(data.table)
setDT(melt(mat))[, L1 := seq_len(.N), L1][]
#    value L1
# 1:     5  1
# 2:     1  1
# 3:     4  2
# 4:     5  3
# 5:     3  1
# 6:     1  2
# 7:     4  1
# 8:     6  2
# 9:     5  3
#10:     3  4
``````