2017-07-20 67 views
0

元素考虑data.table,exampleDT应用功能子集满足跨列的子集标准,data.table

set.seed(7) 
exampleDT = data.table(colA = rnorm(10,15,5), 
         colB = runif(10,100,150), 
         targetA = rnorm(10,12,2), 
         targetB = rnorm(10,8,4)) 

如果我想计算targetA列中的所有元素的平均值,为例如,在低于某一阈值 - 说,10 - 我能做到以下几点:

examp_threshold = 10 
exampleDT[targetA<examp_threshold,mean(targetA)] 
# [1] 9.224007566814299 

如果我要计算在列targetAtargetB所有元素,例如平均,我可以做如下:

target_cols = names(exampleDT)[which(names(exampleDT) %like% "target")] 
exampleDT[,lapply(.SD,mean),.SDcols=target_cols] 
#    targetA   targetB 
# 1: 12.60101574551183 7.585007905896557 

但我不知道如何将两者结合起来;也就是计算所有包含指定字符串(本例中为“目标”)的列中所有元素的均值,它们低于某个指定的阈值(此处为10)。这是我第一次的猜测,但它是不成功的:

exampleDT[.SD<examp_threshold,lapply(.SD,mean),.SDcols=target_cols] 
#Empty data.table (0 rows) of 2 cols: targetA,targetB 

回答

2

您需要在j表达集,像这样:

exampleDT[, lapply(.SD, function(x) mean(x[x<examp_threshold])),.SDcols=target_cols] 

# targetA targetB 
#1: 9.224008 6.66624 
+0

完美!非常感谢! –