lapply 如果在 data.table

lapply and if in data.table

我想在我的 data.table 中检查以下内容:

删除Rt或Rt-1大于300%且(1+Rt)(1+Rt-1)-1小于50%的returns。

现在我有一个 data.table 有很多 return 列,其中每个列代表一个公司,行是特定于日期的,return 是 在 Data.table 返回 DS01 中,它们也有缺失值 (NA)。

我尝试通过以下代码应用它:

ReturnsNEW <- ReturnsDS01[,lapply(.SD, function(x) ifelse((x > 3 || shift(x, fill = NA) > 3) && ((1+x)(1+shift(x, fill = NA))-1)) < 0.5, x = NA, x=x), .SDcols = names(ReturnsDS01)[sapply(ReturnsDS01, is.numeric)]]

我的目标是通过 ifelse 函数来实现: 如果 x 大于 3 或 shift(x) 大于 3 AND (1+x)*(1+shift(x))-1 小于 0.5,则设置 x = NA.

第一个问题:代码不工作,我收到以下错误

Error in FUN(X[[i]], ...) : 
  formal argument "x" matched by multiple actual arguments

第二个问题:如果 x 和 shift(x) 满足这些条件,我想将它们都分配给 NA,但我不知道 c(x, shift(x)) = NA 是如何工作的。

有人可以帮我一下吗?

提前致谢。

第一期

有很多语法问题,例如:

  • 应该使用“|”和“&”相对于“||”或“&&”比较向量时
  • 不需要使用"x=NA"或"x=x",只需使用"NA,x)"作为ifelse
  • 乘以 2 brucket,你需要一个“*”在
  • 之间
  • brukets 不匹配...

因此代码对我来说是这样的:

ReturnsDS01 = data.table(a = runif(10,0,1),b = runif(10,0,1))
numericVar = names(ReturnsDS01)[sapply(ReturnsDS01, is.numeric)]
lagNew  <- function(x) ifelse((x > 3 | shift(x) > 3) & (1+x)*(1+shift(x))-1 < 0.5, NA, x)
ReturnsNEW <- ReturnsDS01[,lapply(.SD, lagNew), .SDcols = numericVar]

第二期

您可能需要稍微修改一下功能,例如:

ReturnsDS01 = data.table(a = runif(10,0,1),b = runif(10,0,1))
ReturnsDS01$a[3] = 4
ReturnsDS01$a[2] = -0.9
lagNew  <- function(x) {
  ind = which((x > 3 | shift(x) > 3) & (1+x)*(1+shift(x))-1 < 0.5)
  x[ind] = NA
  x[setdiff(ind-1,0)] = NA
  x
}

ReturnsNEW <- ReturnsDS01[,lapply(.SD, lagNew), .SDcols = numericVar]