删除异常值的用户函数

user function to remove outliers

使用 10 x 10 矩阵来说明问题,请参见下文。

我有兴趣了解如何创建 用户函数 以从某些数据列中删除离群值。有很多好方法可以解决我的查询,例如。但是更愿意了解如何使用用户功能。

我的基本公式-

Outliers <- boxplot (t$Yn)$out

其中 n = x1、x4、x7

t1_out <- t[-c(which(t$X1)%in%outliers)),]
t4_out <- t[-c(which(t$X4)%in%outliers)),]
t7_out <- t[-c(which(t$X7)%in%outliers)),]

我的问题 - 如何使用以下方法创建用户函数来执行 t$X1、t$X4、t$X7 的操作?

function_name <- function (arg1, arg2, ...){
  statements  # do useful stuff 
  object      # return something
}

我面临的挑战是理解如何在用户公式中处理两个操作。

example <- data.frame(X1 = sample(c(1, 2, 5, 40:60, 98, 99), 50, TRUE),
                      X2 = sample(c(1, 2, 3, 40:60, 92, 99), 50, TRUE),
                      X3 = sample(c(1, 2, 7, 40:60, 97, 98), 50, TRUE))
head(example, 10)
boxplot(example)

clean <- function(v){
  bp <- boxplot.stats(v)
  v[-which(v %in% bp$out)]
}

boxplot(example$X1, clean(example$X1),
        example$X2, clean(example$X2),
        example$X3, clean(example$X3),
        col = c("blue", "red"))
legend("topright", fill = c("blue", "red"), legend = c("before clean", "after clean"))

函数 clean 接受一个数字向量,returns 它没有异常值(由 boxplot.stats 定义),就像您所做的那样。

vector <- rbeta(50, 10, 1)
plot(density(vector))
lines(density(clean(vector)), col = "red")