## 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 )

We can use basic operations:

Alternatively,

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.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'