forked from tom13878/pro-gap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winsor.R
51 lines (45 loc) · 1.13 KB
/
winsor.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
winsor <- function(x, fraction=0.05, lower=TRUE, upper=TRUE){
# Winsor functions at a quantile chosen by fraction
if (length(fraction) != 1 || fraction < 0 || fraction > 0.1){
stop('bad choice of fraction!!')
}
q <- quantile(x, probs = c(fraction, 1-fraction), na.rm = TRUE)
ll <- q[1]
ul <- q[2]
if(lower){
x[x < ll] <- ll
}
if(upper){
x[x > ul] <- ul
}
return(x)
}
winsor2 <- function (x, multiple=3){
# winsor function by so many multiples from median average
# deviation
if(length(multiple) != 1 || multiple <= 0) {
stop("bad value for 'multiple'")
}
med <- median(x, na.rm = TRUE)
y <- x - med
sc <- mad(y, center=0, na.rm = TRUE) * multiple
y[ y > sc ] <- sc
y[ y < -sc ] <- -sc
y + med
}
trim <- function(x, fraction=0.05, lower=TRUE, upper=TRUE){
# set values below or above a certain quantile to NA
if (length(fraction) != 1 || fraction < 0 || fraction > 0.1){
stop('bad choice of fraction!!')
}
q <- quantile(x, probs = c(fraction, 1-fraction), na.rm = TRUE)
ll <- q[1]
ul <- q[2]
if(lower){
x[x < ll] <- NA
}
if(upper){
x[x > ul] <- NA
}
return(x)
}