首页 > 解决方案 > 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.)

标签: rapply

解决方案


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

推荐阅读