首页 > 解决方案 > R当没有足够的行时,在data.table中按组查找正在运行的相关性

问题描述

我正在尝试使用 runCor 按组查找运行相关性。由于最后一个 Team 只有一个元素,因此该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 团队),因为找不到相关性并NA为 T9 填写 r 列?

谢谢!

标签: rdata.tablequantmod

解决方案


如果出现错误,您可以使用tryCatch返回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

推荐阅读