R 当不存在足够的行时,在 data.table 中按组查找 运行 相关性

R Finding the running correlation by group in data.table when enough rows does not exist

我正在尝试使用 runCor 按组查找 运行 相关性。由于最后一个团队只有一个元素,因此 runCor 函数抛出错误。

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]

有没有办法抓住这种情况(T9 团队),因为找不到相关性并在 T9 的 r 列中填写 NA

谢谢!

您可以使用 tryCatch 到 return NA 以防出错:

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