I am trying to find running correlation by group using runCor. Since the last Team has just one element, the runCor
function is throwing the error.
library(data.table)
library(TTR)
dat <- data.table(
Team = sapply(1:32, function(x) paste0("T", x)),
Year = c(rep(c(2000:2009), 32)),
Points_Game = c(rnorm(320, 100, 10))
)
dat = dat[order(Team, Year)][1:311]
# find correlation of Year and Points_Game for each Team
dat = dat[ , r := TTR::runCor(Year, Points_Game, n = 3), by = Team]
Is there a way to catch this case (T9 team) as correlation cannot be found and to fill NA
in column r for T9?
Thanks!
You could use tryCatch
to return NA
in case of error:
runCorProtected <- function(...) {
tryCatch(TTR::runCor(...),error = function(e) {NA})
}
dat = dat[ , r := runCorProtected(Year, Points_Game, n = 3), by = Team]
dat[Team=='T9']
Team Year Points_Game r
1: T9 2000 103.1672 NA