[R-sig-teaching] subsetting data with the median position

Peter Meissner peter.meissner at uni-konstanz.de
Tue Dec 22 21:57:29 CET 2015


hmmm, maybe those were a little shortsighted and fasttyped... 

> 
> dat1 <- c(2,4,8,9,11,11,11,12,15)
> 
> dat1[dat1 > median(dat1)]
> [1] 12 15
> dat1[dat1 < median(dat1)]
> [1] 2 4 8 9
> 

.. but that should reliably split:

median_split <- function(x){
  n <- floor(length(x) / 2) 
  x <- sort(x)
  list(head(x, n), tail(x, n))
}

median_split(c(2, 4, 8, 9,11,11,12))
## [[1]]
## [1] 2 4 8
## 
## [[2]]
## [1] 11 11 12

median_split(c(2,4,8,9,11,11,11,12,15))
## [[1]]
## [1] 2 4 8 9
## 
## [[2]]
v[1] 11 11 12 15

median_split(0)
## [[1]]
## numeric(0)
## 
## [[2]]
## numeric(0)


best, peter

	[[alternative HTML version deleted]]



More information about the R-sig-teaching mailing list