I have a network dataset of adolescents friendship nominations. I want to calculate the density for each of the ego's local network, and ideally create a new data frame with the ego's id number and their ego network density score.
Sample edgelist:
df<-read.table(text="student_id alter
1 3
2 5
2 2
2 3
3 2
3 4
3 5
4 1
4 6
4 3
5 1
5 6
5 2
6 5
6 2
6 1
7 8
8 9
9 8
9 7
10 7
10 9
11 19
11 15
11 12
12 20
12 19
12 11
13 15
13 19
13 11
14 16
14 12
14 18
15 17
15 20
15 17
16 14
16 19
16 20
16 13
17 20
17 18
17 13
17 14
18 13
18 19
18 17
19 17
19 16
19 11
20 13
20 17
20 11
20 1", header = TRUE)
Desired output:
student_id egonet_density
1 0.5000000
2 0.7500000
3 0.5500000
4 0.5000000
5 0.6000000
6 0.5000000
7 0.5000000
8 0.6666667
9 0.5000000
10 0.5000000
11 0.4333333
12 0.4500000
13 0.4107143
14 0.4000000
15 0.5500000
16 0.4500000
17 0.4047619
18 0.4500000
19 0.3809524
20 0.3750000
This is the code I've tried so far. The issue is that densities df only has the density values, it does not include the ego id numbers. The ego ids aren't consecutive, so I can't just use rowname_to_column for it to work. Any help would be great!
g <- graph_from_data_frame(df, directed = TRUE)
egonet_list <- make_ego_graph(g)
densities <- lapply(egonet_list, graph.density)
densities <- unlist(densities) %>% as.data.frame()