[英]Filtering row with too many max and min in R
My dataset is like below. 我的数据集如下所示。
a_metric b_metric c_metric tl_metric mpr
1 1.0079123 0.4121975 1.0510727 0.5280035 -0.03690215
2 -0.3479917 -0.3185338 -0.3652249 -0.1644014 0.01175352
3 1.7148652 2.7669706 1.8156309 0.6885553 -0.05121204
rate 1st_metric 2nd_metric 3rd_metric 4th_metric IDX
1 -0.7771414 0.2600359 0.3368508 0.3989317 0.4422435 1
2 0.1782411 -0.2824974 -0.3050651 -0.3225591 -0.3318396 2
3 -0.2663647 2.7014838 2.7858352 2.8452738 2.8524606 3
I am trying to filter the row which has maximum value for 1st_metric,2nd_metric,3rd_metric and min value in mpr among the whole data set using the below command 我正在尝试使用以下命令在整个数据集中过滤具有1st_metric,2nd_metric,3rd_metric最大值和mpr最小值的行
k[(which.max(k$1st_metric))&(which.max(k$2nd_metric))&(which.max(k$3rd_metric))&(which.min(k$mpr)),]
Instead of returning the 3rd row it returns the entire dataset. 而不是返回第三行,而是返回整个数据集。 What am I doing wrong here?
我在这里做错了什么?
What your code actually is evaluated as 您的代码实际被评估为
k[3 & 3 & 3 & 3]
If you type 3 & 3 & 3 & 3
in console it gives you #[1] TRUE
. 如果您在控制台中键入
3 & 3 & 3 & 3
,它将为您提供#[1] TRUE
。
So it returns k[TRUE]
which selects the entire data frame. 因此它返回
k[TRUE]
,它将选择整个数据帧。
What you need is some condition which evaluates to k[3, ]
您需要的是一些条件,其结果为
k[3, ]
We can use, 我们可以用,
k[which(k$X1st_metric == max(k$X1st_metric) & k$X2nd_metric == max(k$X2nd_metric)
& k$X3rd_metric == max(k$X3rd_metric) & k$mpr == min(k$mpr)), ]
# a_metric b_metric c_metric tl_metric mpr rate
#3 1.714865 2.766971 1.815631 0.6885553 -0.05121204 -0.2663647
# X1st_metric X2nd_metric X3rd_metric X4th_metric IDX
#3 2.701484 2.785835 2.845274 2.852461 3
Or by modifying your code 或通过修改您的代码
k[unique(c(which.max(k$X1st_metric), which.max(k$X2nd_metric) ,
which.max(k$X3rd_metric) , which.min(k$mpr))), ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.