【问题标题】:user function to remove outliers [closed]删除异常值的用户功能[关闭]
【发布时间】:2021-07-14 13:45:48
【问题描述】:

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

我有兴趣了解如何创建 用户函数 以从某些数据列中删除异常值。有很多好方法可以解决我的查询,例如Adapting a code for removing outliers- Function not running in loop。但更愿意了解如何使用用户功能。

我的基本公式 -

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
}

对我来说,挑战在于理解如何在用户公式中使用两个操作。

【问题讨论】:

  • 您能否编辑您的问题以将您的示例矩阵包含为 text(即剪切并粘贴到代码块中)而不是图像?如果您不确定如何编辑,您可以转储文本,有人会帮助您正确格式化...
  • 还有,你能澄清一下“用户功能”是什么意思吗?
  • 感谢 Ben 提供编辑建议,我还在学习。 'User Function' - 由用户定义的函数,用于执行未内置于 r 中的操作(例如 sum()、mean() 等)

标签: r outliers


【解决方案1】:
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 接受一个数字向量,并按照您所做的方式返回不包含异常值(由 boxplot.stats 定义)的向量。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 2019-05-12
    • 2016-06-28
    • 2015-03-15
    • 2021-12-18
    • 1970-01-01
    • 2012-05-24
    相关资源
    最近更新 更多