我有一个如下的数据框:
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) 只包括不在UL和LL(Zoutliers)之间的行。
c) 然后计算Zoutlier与前一个或后一个同一chr行的方向相同(即正或负)的行数。
因此输出结果为:
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部分组合在一起,以获得我想要的输出结果。
3:ncol(df)
,还是只指一列? - Carl Witthoft