I have created origin destination matrices for different weeks in the year, e.g. the output looks like:
Region 1 | Region 2 | Region 3 | |
---|---|---|---|
Region 1 | 0 | 8 | 1 |
Region 2 | 4 | 3 | 3 |
Region 3 | 2 | 2 | 3 |
Week 1
I have similar looking matrices for all weeks of the year, all representing activity between each pair of nodes. Now, I want to compute a dataframe which shows activity for all different pairs of origin-destination (13x13) per week in the year. How can I code this using R?
Obviously we don't have your data. I'll create a little example data set here so you can see one approach that should work for you.
Suppose I have three matrices representing three weeks:
(The code to recreate these matrices is shown at the bottom of this answer in a format you can copy and paste to your R console).
The first thing to do is to get all your matrices into a list (if they are not already)
Now you can
melt
the matrices into data frames. Rather than doing this one at a times, we can do them all at once now that they are in a list by callinglapply
:This will give us a list of data frames, one for each week. Now we need to bind these together into a single long data frame.
Lastly, we want to add an extra column to the data frame so that we know which week the data comes from:
And this gives us the final result:
Created on 2022-03-11 by the reprex package (v2.0.1)
Data