How do I get the average similarity score by country in a matrix?

Viewed 21

I have a dataframe that shows treaties between two countries, and I did a similarity matrix on the text. I now have the similarity percentage between treaty pairs. I want to get the average text similarity percentage by country. I tried to reshape the dataframe but I can't group them by country or get the code to identify different countries. This is what my df looks like.

    structure(list(similarity = c(1, 1, 0.50311221359869, 0.50311221359869), 
    number = c("PTA1", "PTA2", "PTA1", "PTA2"), pta = c("1003", "1003", "1012", 
    "1003"), country1 = c("Brazil", "Brazil", "Ecuador", 
    "Brazil"), country2 = c("Venezuela", "Venezuela", "El Salvador", 
    "Venezuela"), name = c("Brazil Venezuela", "Brazil Venezuela", 
    "Ecuador El Salvador", "Brazil Venezuela")), row.names = c(NA, 
    -4L), class = c("tbl_df", "tbl", "data.frame"))

    
1 Answers

The code below worked for me on replit.

First it converts your structure into a tibble so it plays nice with dplyr, then group by one of the country columns, and finally summarize.

library('tidyverse')
x <-structure(list(similarity = c(1, 1, 0.50311221359869, 0.50311221359869), 
number = c("PTA1", "PTA2", "PTA1", "PTA2"), pta = c("1003", "1003", "1012", 
"1003"), country1 = c("Brazil", "Brazil", "Ecuador", 
"Brazil"), country2 = c("Venezuela", "Venezuela", "El Salvador", 
"Venezuela"), name = c("Brazil Venezuela", "Brazil Venezuela", 
"Ecuador El Salvador", "Brazil Venezuela")), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

x %>% as_tibble %>%
    group_by(country1) %>%
    summarize(mean_similarity = mean(similarity))
Related