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
如果我要计算在列targetA
和targetB
所有元素,例如平均,我可以做如下:
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
完美!非常感谢! –