[R] Winsorisation function

dms at riseup.net dms at riseup.net
Wed Nov 14 22:05:20 CET 2012


Dear all,
someone  can find what I doing wrong with the following function. It is
for winsorisation mean. At my eyes it is ok, but for reason I sometimes it
is changing the results when I change the k value.

wmean <-
function (x, na.rm = FALSE, k = 1) {
        if (any(i.na <- is.na(x))) {
            if (na.rm)
                x <- x[!i.na]
            else return(NA)
        }
		n <- length(x)
        if (!(k %in% (0:n)))
            stop("Invalid argument for 'k'.")
		x <- sort(x)
		x[1:k] <- x[k+1] # Here I solve the lower values
		x[(n-k+1):n] <- x[n-k] #Then I go over the higher ones
		return(mean(x))
	}


set.seed(51)
a<- sample(200,100)

> wmean(a, k=5)
[1] 95.85
> wmean(a, k=6)
[1] 95.91
> wmean(a, k=7)
[1] 95.91
> wmean(a, k=8)



More information about the R-help mailing list