While Sacha's solution is fairly general, median (or other quantiles) are order statistics, so you can calculate the corresponding indices from order (x) (instead of sort (x) for quantile values).
Looking at quantile , you can use types 1 or 3, all the rest lead to (weighted) average values ββof the two values ββin some cases.
I chose type 3, and copying and pasting a little from quantile results in:
which.quantile <- function (x, probs, na.rm = FALSE){ if (! na.rm & any (is.na (x))) return (rep (NA_integer_, length (probs))) o <- order (x) n <- sum (! is.na (x)) o <- o [seq_len (n)] nppm <- n * probs - 0.5 j <- floor(nppm) h <- ifelse((nppm == j) & ((j%%2L) == 0L), 0, 1) j <- j + h j [j == 0] <- 1 o[j] }
A small test:
> x <-c (2.34, 5.83, NA, 9.34, 8.53, 6.42, NA, 8.07, NA, 0.77) > probs <- c (0, .23, .5, .6, 1) > which.quantile (x, probs, na.rm = TRUE) [1] 10 1 6 6 4 > x [which.quantile (x, probs, na.rm = TRUE)] == quantile (x, probs, na.rm = TRUE, type = 3) 0% 23% 50% 60% 100% TRUE TRUE TRUE TRUE TRUE
Here is your example:
> dat [which.quantile (dat$V4, c (0, .5, 1)),] V1 V2 V3 V4 7 7 0.4874291 -0.01619026 1 2 2 0.1836433 0.38984324 13 1 1 -0.6264538 1.51178117 17