Group_by with correlation in R

Viewed 31

Hey I want to calculate pairwise correlation or if you have any other ideas another measure to see if values have a statistic correlation/relationship.

This is my example dataframe:

df <- data.frame(ID_A = c("1", "1", "1", "2", "2", "2", "2"),
                 ID_B = c("A", "A", "A", "B", "B", "C", "C"),
                 Year = c("2020", "2021", "2022", "2019", "2020", "2021", "2022"),
                 Value = c(0.4, 0.5, 0.45, 0.4, 0.5, 0.8, 0.85))

I would like to calculate a measure/correlation to see if there is a correlation in the performance (Values) over the years for group_by ID_A and ID_B.

cor_df = df %>% group_by(ID_A, ID_B) %>%
  summarise(correlation = cor(Value, use = "pairwise"))

Caused by error in cor(): ! supply both 'x' and 'y' or a matrix-like 'x'

How can I make this work? I know cor needs x and y, but I can't find a way with my approach. My goal would be a table like this:

ID_A ID_B Correlation/Measure
1 A 0.8
2 B 0.6
2 C 0.1

(Correlation/Measure values are made up)

1 Answers

You can pass Year value in cor() function after changing it to numeric.

library(dplyr)
  
df %>%
  mutate(Year = as.numeric(Year)) %>%
  group_by(ID_A, ID_B) %>%
  summarise(cor_value = cor(Value, Year, use = "pairwise"), .groups = "drop")

#  ID_A  ID_B  cor_value
#  <chr> <chr>     <dbl>
#1 1     A           0.5
#2 2     B           1  
#3 2     C           1  
Related