I am working on a large dataset. However I will start with a small example to illustrate what I am trying to achieve.
I have the following vectors:
season <- c("2019")
round <- c("1")
team <- c("Team A", "Team B", "Team C")
margin <- c(33, 56, 63)
score_A <- c(0.330, 0.256, 0.118)
score_B <- c(0.584, 0.176, 0.342)
score_C <- c(0.118, 0.193, 0.286)
And I create a data frame like so:
df1 <- data.frame(season, round, team, score_A, score_B, score_C, margin)
I then apply weightings to each of the scores like:
df1$score_A <- df1$score_A * 0.25
df1$score_B <- df1$score_B * 0.5
df1$score_C <- df1$score_C * 0.75
I then sum all the scores and create a team total score:
df1$score_total <- df1$score_A + df1$score_B + df1$score_C
library(dplyr)
df1 <- df1%>%group_by(season, round, team)%>%dplyr::mutate(score_Team_Total=sum(score_total))
I know that I can then calculate the Pearson like so:
> cor(df1$margin, df1$score_Team_Total, method = "pearson")
[1] -0.5505451
Although this does not give me a line by line return, I am not quite sure yet how to calculate that.
However this is where it starts to get tricky.
I have a number of weightings that I would like to apply to each of the scores like so:
weightings <- c(0.25,0.5,0.75,1,1.25,1.5,2,2.5,3)
And I have a number of scores for each weighting (score_A right through to score_R).
The first combination would be:
df1$score_A <- df1$score_A * 0.25
df1$score_B <- df1$score_B * 0.25
df1$score_C <- df1$score_C * 0.25
The second combination would be:
df1$score_A <- df1$score_A * 0.25
df1$score_B <- df1$score_B * 0.25
df1$score_C <- df1$score_C * 0.5
The third combination would be:
df1$score_A <- df1$score_A * 0.25
df1$score_B <- df1$score_B * 0.5
df1$score_C <- df1$score_C * 0.5
And so on.
But how can I get the Pearson correlation for each combination and return the highest possible Pearson?
I know there will be millions of comibations, as I ran this:
> length(permutations(7, 9, repeats.allowed = TRUE))
[1] 363182463
But I have 9 different variables in my weightings (0.25,0.5,0.75,1,1.25,1.5,2,2.5,3) and 18 different scores (score_A through to score_R).
So when I tried:
> length(permutations(9, 18, repeats.allowed = TRUE))
I received this error:
Error: cannot allocate vector of size 73.7 Gb
So I know the number is going to be very large.
I need to apply each combination of weightings to the scores, then create the totals and calculate the Pearson.
A dataframe or list with the results would be too large I assume, so is there a way to return the optimal comination? The output would look something like:
score_A score_B score_C pearson
weighting 0.25 0.50 0.25 0.63
I am still new to R and learning so I am not quite sure where to go from here.