How to compute average closeness of ego subnetwork based on alter attributes in R?

17 Views Asked by At

I have ego-network data. Participants categorized 3 of their friends as A, B, or C. Then, they rated how close they are to one another.

I want to create a column with the average closeness between each participant's friends categorized as type "C".

For example, for the first row, only "friend1_closeness_friend2" would be used in the calculation and "friend1_closeness_friend3" and "friend2_closeness_friend3" would be ignored.

library(dplyr)

data <- data.frame(
  ID = c("001", "002", "003"),
  friendshipType_1 = c("C", "C", "A"),
  friendshipType_2 = c("C", "C", "B"),
  friendshipType_3 = c("A", "C" , "A"),
  friend1_closeness_friend2 = c(1, 2, 3),
  friend1_closeness_friend3 = c(4, 3, 2),
  friend2_closeness_friend3 = c(1, 1, 2)
)

Desired output:

data <- data.frame(
  ID = c("001", "002", "003"),
  friendshipType_1 = c("C", "C", "A"),
  friendshipType_2 = c("C", "C", "B"),
  friendshipType_3 = c("A", "C" , "A"),
  friend1_closeness_friend2 = c(1, 2, 3),
  friend1_closeness_friend3 = c(4, 3, 2),
  friend2_closeness_friend3 = c(1, 1, 2),
  mean_c = c(1, 2, NA)
)
1

There are 1 best solutions below

0
Bruce On

Maybe you can achieve this using dplyr and rowwise() operation to calculate the mean closeness for each row based on the friendship type specified. Here's how you can do it:

  data2 <- data %>%
  rowwise() %>%
  mutate(mean_c = mean(c(friend1_closeness_friend2, friend1_closeness_friend3, friend2_closeness_friend3)[c(friendshipType_1, friendshipType_2, friendshipType_3) == "C"], na.rm = TRUE))

the mean_c column represents the mean closeness among friends categorized as type "C" for each participant. Hope it helps you!