I would like to compute the standard deviation for each row in a data frame over a selection of columns after removing the minimum and the maximum in that selection. Here is an example:
set.seed(1)
dat <- data.frame(matrix(sample(c(1:100), 10, replace=TRUE), ncol=5))
I managed to calculate the sd of my columns of interest (1:4) for each row:
dat <- transform(dat, sd = apply(dat[,1:4], 1, sd))
show(dat)
X1 X2 X3 X4 X5 sd
1 27 58 21 95 63 33.95463
2 38 91 90 67 7 24.93324
However, I can't figure out how to exclude min(dat[1,1:4])
and max(dat[1,1:4])
before calculating sd()
.
The result should be this:
X1 X2 X3 X4 X5 sd
1 27 58 21 95 63 21.92031 # notice: sd calculated by hand using 'sd(c(27,58))'
2 38 91 90 67 7 16.26346 # notice: sd calculated by hand using 'sd(c(67,90))'
Can someone help me with this?