r - 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 列?
谢谢!
解决方案
如果出现错误,您可以使用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
推荐阅读
- firebase - 运行失败:在合并时部署到 Firebase 托管 - 主
- javascript - 阻止输入类型 date null 时更改边框颜色和消息 html 验证
- three.js - 在 React-Three-Fiber 中移动平面顶点位置的正确方法
- oauth-2.0 - 使用带有 OAuth2.0 客户端凭据的 Azure EWS 发送电子邮件
- javascript - 如何将多个类名添加到 nextjs 元素
- google-sheets - 将html表格行提取到谷歌表格
- python - Python`urllib3`:突然“证书验证失败:证书已过期”错误
- python - 截至 2021 年,Google Colab 使用的是哪个 Python 版本?
- c# - 发布操作在控制器中不起作用但在另一个控制器中起作用
- sql - 如何在特定值更改 SQL/Hive 后播种/插入特定值