# Create a list of distance matrices in R

Using the Cshapes package in R, I want to create a list of matrices that measure for each year whether two countries are neigbors or not.

install.packages("cshapes")

Running the code for one year (here 1990) works fine:

wmat <- distmatrix(as.Date("1990-1-1"), type="mindist", tolerance=0.5, useGW=FALSE)

This gives a matrix with the following structure:

A B C D 1 A 0 0 210 0 2 B 0 0 637 305 3 C 210 637 0 73 4 D 0 305 73 0

In a next step, I set all combinations with 0 distance between two countries to 1, all other combinations to 0, and the diagonal to 0 again:

wmat[wmat>0]<-5 wmat[wmat==0]<-1 wmat[wmat==5]<-0 diag(wmat)<-0

This gives me following matrix:

A B C D 1 A 0 1 0 1 2 B 1 0 0 0 3 C 0 0 0 0 4 D 1 0 0 0

What I struggle to do is to automatically create matrices for all the years between 1960 and 2014, do the corrections for each year and store the results into a list of matrices where I can recall each matrix by the respective year.

Any inputs are highly welcome.

## Answers

You could try

lst <- lapply(1960:2014, function(x) { wmat <- distmatrix(as.Date(paste0(x, '-1-1')), type="mindist", tolerance=0.5, useGW=FALSE) wmat[wmat>0]<-5 wmat[wmat==0]<-1 wmat[wmat==5]<-0 diag(wmat)<-0 wmat } )