My data frame consists of individuals and the city they live at a point in time. I would like to generate one origin-destination matrix for each year, which records the numb
You could use reshape2's dcast and a loop to do this.
library(reshape2)
# write function
write_matrices <- function(year){
mat <- dcast(subset(df, df$year_move == year), origin ~ destination)
print(year)
print(mat)
}
# get unique list of years (there was an NA in there, so that's why this is longer than it needs to be
years <- unique(subset(df, is.na(df$year_move) == FALSE)$year_move)
# loop though and get results
for (year in years){
write_matrices(year)
}
The only thing this doesn't address is the requirement for each matrix to have 5*5, because if some years do not have all the 5 cities only cities in that year are shown.
You could fix this by adding a step in that turns your observations into a frequency table first, so they are included but as zeros.