I have information on physicians working in different hospitals at different points in time. I would like to define networks at the hospital-month level so that peers are physicians who work together in the same hospital at the same time. Because a physician can work in more than one hospital at the same time, the network groups partially overlap.
I would like, then, to compute basic descriptives of the resulting network (e.g. average degree, density, clustering) at the month level so as to see how these change over time.
Consider the very simple example of hospitals x-y-w, periods 1-2 and physicians A-B-C-D.
- Physicians A, B and C work in hospital x at period 1
- Physicians A and B work in hospital x at period 2
- Physician A works in hospital y at period 1
- Physicians A and C work in hospital y at period 2
- Physicians C and D work in hospital w at period 1
- Physicians A and D work in hospital w at period 2
This is represented in the dataframe below.
mydf <- data.frame(hospital = c("x","x","x","x","x","y","y","y","w","w","w","w"),
period = c(1,1,1,2,2,1,2,2,1,1,2,2),
physician = c("A","B","C","A","B","A","A","C","C","D","A","D"))
For now, I have writen the code below. First, I construct a dataframe with every pair of physician in a given hospital-month. Second, I filter the pairs for each period. Third, I define one igraph object for each period. Fourth, I plot the graphs and compute the descriptive stats (e.g. density) for each period. Is there any simpler way to do this? If not how could I automate this code for many periods?
relations <- mydf %>%
rename(from = physician) %>%
left_join(mydf, by=c("hospital","period")) %>%
rename(to = physician) %>%
filter(from!=to) %>%
relocate(from, to)
relations_1 <- relations %>%
filter(period==1)
relations_2 <- relations %>%
filter(period==2)
g1 <- simplify(graph_from_data_frame(relations_1, directed=FALSE, vertices=NULL))
g2 <- simplify(graph_from_data_frame(relations_2, directed=FALSE, vertices=NULL))
plot(g1)
plot(g2)
degree(g1)
degree(g2)