Ester Silva
Ester Silva

Reputation: 680

creating a Sparse matrix from a list of lists- R

I have a list called res which includes 83 lists with the following format. I need to generate one sparse matrix out of these lists. Row and Columns are indecies for the row and column of the sparse matrix and freq is the entry for that corresponding index.

Example of format for res[82] and res[83]:

[[82]]
   Row Columns Freq
2   82      33    1
3   82     173    1
4   82     211    1
5   82     247    2
6   82     480    2
7   82     541    1
8   82     974    1
9   82    1197    1
10  82    1416    1
11  82    1531    1
12  82    1797    7
13  82    2416    2
14  82    2530    1
15  82    2772    1
16  82    2970    2
17  82    3264    4
18  82    3416    1
19  82    3995    4
20  82    5593    1
21  82    6557    1
22  82    8141    1
23  82    9044    1
24  82   11889    1
25  82   12608    1
26  82   13352    1
27  82   13463    1
28  82   17937    1
29  82   29730    1
30  82   37712    1
31  82  258434    1

[[83]]
   Row Columns Freq
2   83     309    1
3   83     447    1
4   83     480    2
5   83     487    1
6   83     619    1
7   83     651    1
8   83     913    1
9   83    1555    1
10  83    1874    1
11  83    2416    1
12  83    3101    1
13  83    3856    1
14  83    3964    1
15  83    3995    1
16  83    4017    1
17  83    4362    1
18  83   10551    1
19  83   17130    1
20  83   29730    1

Upvotes: 0

Views: 246

Answers (1)

akrun
akrun

Reputation: 887158

We can use sparseMatrix from Matrix after rbinding the list elements.

library(Matrix)
d1 <- do.call(rbind, lst)
res <- sparseMatrix(d1[,1], d1[,2], x = d1[,3])

Upvotes: 1

Related Questions