r - Excluding both the minimum and maximum value
问题描述
I want to exclude the minimum as well as the maximum value of each row in a data frame. (If one of those value are repeated, only one should be excluded.)
I can exclude either the minimum, or the maximum, but not both. I don't seem to find a way to combine those (which both work fine by themselves):
d[-which(d == min(d))[1]]
d[-which(d == max(d))[1]]
This doesn't work:
d[
-which(d == min(d))[1] &
-which(d == max(d))[1]
]
It gives the full row.
(I also tried an approach using apply(d, 1, min/max), but this also fails.)
解决方案
Update
Remembered after looking at @Rich Pauloo's answer, we can directly use which.max
and which.min
to get index of minimum and maximum value
as.data.frame(t(apply(df, 1, function(x) x[-c(which.max(x), which.min(x))])))
# V1 V2 V3
#1 13 11 6
#2 15 8 18
#3 5 10 21
#4 14 12 17
#5 19 9 20
Here which.max
/which.min
will ensure that you get the index of first minimum and maximum respectively for each row.
Some other variations could be
as.data.frame(t(apply(df, 1, function(x)
x[-c(which.max(x == min(x)), which.max(x == max(x)))])))
If you want to use which
we can do
as.data.frame(t(apply(df, 1, function(x)
x[-c(which(x == min(x)[1]), which(x == max(x)[1]))])))
data
set.seed(1234)
df <- as.data.frame(matrix(sample(25), 5, 5))
df
# V1 V2 V3 V4 V5
#1 3 13 11 16 6
#2 15 1 8 25 18
#3 24 5 4 10 21
#4 14 12 17 2 22
#5 19 9 20 7 23
推荐阅读
- php - 连接拒绝 docker、laravel 和 mysql 服务器
- bash - Bash - 用`set`恢复位置参数有什么意义?
- r - 编写一个 for 循环以最小化模糊匹配中的计算
- excel - 如何将 Excel Solver 与 IF 语句一起使用?
- ios - 如何从代表的集合视图单元格中获取 indexPath 项?
- phpspreadsheet - 使用 PhpSpreadsheet 设置电子表格单元格的宽度(像素)
- esp8266 - 当互联网连接从 esp8266 (Nodemcu) 重新连接时,从 .json 文件发送数据集合
- javascript - Spring MVC - 从控制器发布到不同的 url
- python - 从 python 的列表中删除值 / nan / 空字符串(“”)
- php - 如何在 WooCommerce /my-account/downloads/ 中的下载表中添加一列