我有一个数据框如下:
chr leftPos TBGGT 12_try 324Gtt AMN2
1 24352 34 43 19 43
1 53534 2 1 -1 -9
2 34 -15 7 -9 -18
3 3443 -100 -4 4 -9
3 3445 -100 -1 6 -1
3 3667 5 -5 9 5
3 7882 -8 -9 1 3
我必须创建一个循环:
a) 计算从第三列开始的每一列的上限和下限(UL 和 LL)。
b) 只包括掉落的行outsideUL 和 LL (Zoutliers)。
c) 然后计算 Zoutlier 与前一个方向相同(即正或负)的行数or下一行对于同一个字符.
因此,输出将是:
ZScore1 TBGGT 12_try 324Gtt AMN2
nrow 4 6 4 4
到目前为止我的代码如下:
library(data.table)#v1.9.5
f1 <- function(df, ZCol){
#A) Determine the UL and LL and then generate the Zoutliers
UL = median(ZCol, na.rm = TRUE) + alpha*IQR(ZCol, na.rm = TRUE)
LL = median(ZCol, na.rm = TRUE) - alpha*IQR(ZCol, na.rm = TRUE)
Zoutliers <- which(ZCol > UL | ZCol < LL)
#B) Exclude Zoutliers per chr if same direction as previous or subsequent row
na.omit(as.data.table(df)[, {tmp = sign(eval(as.name(ZCol)))
.SD[tmp==shift(tmp) | tmp==shift(tmp, type='lead')]},
by=chr])[, list(.N)]}
nm1 <- paste0(names(df)
setnames(do.call(cbind,lapply(nm1, function(x) f1(df, x))), nm1)[]
该代码是从不同地方修补在一起的。我遇到的问题是将代码的 A) 和 B) 部分组合起来以获得我想要的输出