r - 扫描一列以查找超过某个值的值,并将整个列移动到 R 中的新数据框中
问题描述
x<-matrix(c(0.00009852, -0.00393314, -0.00049056, -0.00117636,
-0.00283716, 0.00136866, -0.00536613, -0.00068090, 0.01528542,
0.01221890, -0.00309366, 0.00379356,-0.00159904, -0.00259300,
-0.00635427, 0.00446363,0.00119367, 0.00079657, 0.00419246,
0.00090068,0.00160321,0.00623682, -0.00010090, -0.00070604),ncol=4)
x<-data.frame(x)
names(x)<-c("active","inactive","injured","rehab")
active inactive injured rehab
1 0.00009852 -0.00536613 -0.00159904 0.00419246
2 -0.00393314 -0.00068090 -0.00259300 0.00090068
3 -0.00049056 0.01528542 -0.00635427 0.00160321
4 -0.00117636 0.01221890 0.00446363 0.00623682
5 -0.00283716 -0.00309366 0.00119367 -0.00010090
6 0.00136866 0.00379356 0.00079657 -0.00070604
所以我有这个数据集叫做(x)。我想要
1) 找出每一列的异常值
2)如果有任何值高于/低于异常值,则扫描列
3) 将具有异常值的列移动到一个名为 y 的新数据框中。
任务1,我使用以下内容:
quantile1<-function(k){
quantile(k, 0.25)+IQR(k)
}
quantile3<-function(k){
quantile(k,0.75)+IQR(k)
}
lower_outlier<-apply(x, 2, quantile1)
upper_outlier<-apply(x, 2, quantile3)
View(t(lower_outlier))
active inactive injured rehab
-0.000048750 0.010112565 0.001094395 0.003545148
View(t(upper_outlier))
active inactive injured rehab
0.00232446 0.0227156 0.0045333 0.0069408
所以现在我对每一列都有上限和下限异常值。如何进行任务 2 和 3?我相信其中一种方法是
x <- x[x <= value]
但我不确定。任何建议都非常感谢
解决方案
我们可以在使比较对象的长度相同(通过复制)后,使用关系运算符创建一个逻辑矩阵,然后得到矩阵colSums
的!
i1 <- !colSums(x > upper_outlier[col(x)] | x < lower_outlier[col(x)])
根据索引对数据集列进行子集化
y <- x[, i1, drop = FALSE]
推荐阅读
- c# - 我如何知道一个列表中的元素是否出现在另一个列表中?
- laravel - Laravel 身份验证中的 TokenMisMatchException
- ruby - 使用命令行参数调用方法时出错
- javascript - 如何停止递归函数修改它自己的变量?
- javascript - 更改 eventListener 调用的函数内的变量不起作用
- python - 如何在 pytorch 中使用 'DataLoader(dataset=Dataset(train_data, train_label))' 而我没有输入整个 'train_data'?
- php - laravel 如何调用不在类和父类中的方法
- android - Android R8 Code Shrinker 和 AWS CodePipeLine:java.lang.StackOverflowError(无错误消息)
- java - 不可编辑的自动滚动 JTextArea
- reactjs - 静态 Gatsby 页面中是否可以有动态 React 组件?