【问题标题】:Replacing values in df using index使用索引替换 df 中的值
【发布时间】:2017-02-06 12:40:59
【问题描述】:

我正在尝试检测我的数据框中的异常值并用 NA 替换异常值。 我稍微修改了这里提供的功能:How to repeat the Grubbs test and flag the outliers。在尝试矢量函数时效果很好,但我的问题是当我在数据帧上使用它时。该函数检测异常值,但我不知道如何将结果作为数据框。

我想要的结果是将我的原始数据框替换为NAs。其中NA将是检测到的异常值。

这是我到目前为止所尝试的:

library(outliers)
data("rock")

# Function to detect outliers with Grubbs test in a vector
grubbs.flag <- function(vector) {
outliers <- NULL
test <- vector
grubbs.result <- grubbs.test(test)
pv <- grubbs.result$p.value
# throw an error if there are too few values for the Grubb's test
 if (length(test) < 3 ) stop("Grubb's test requires > 2 input values")
 while(pv < 0.05) {
outliers <- c(outliers,as.numeric(strsplit(grubbs.result$alternative," ")[[1]][3]))
test <- vector[!vector %in% outliers]
# stop if all but two values are flagged as outliers
if (length(test) < 3 ) {
  warning("All but two values flagged as outliers")
  break
}
grubbs.result <- grubbs.test(test)
pv <- grubbs.result$p.value
idx.outlier <- which(vector %in% outliers)
na.vect <- replace(vector, idx.outlier, NA)

}
return(na.vect)
}

# Function to detect outliers with Grubbs test in a dataframe
Grubbs.df <- function(data){
grubbs.data <- (as.vector(unlist(apply(data, grubbs.flag))))
return(grubbs.data)
}

知道如何进行这项工作吗?

【问题讨论】:

  • 我猜想与脚本末尾的 apply 和 as.vector 有关。我会在我的笔记本电脑上运行它,看看发生了什么。

标签: r outliers


【解决方案1】:

你应该在 while 循环之前添加这个:

na.vect <- test

因为如果它事先中断,您的 na.vect 将不存在,因此会引发错误。然后像这样在你的数据框上运行它:

apply(rock,2,grubbs.flag)

第二个参数 2 告诉将其应用于数据框的列。使用 1 表示行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2019-12-22
    • 1970-01-01
    • 2023-04-09
    • 2014-04-29
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多