R 使用索引替换df中的值
我正在尝试检测数据帧中的异常值,并用NAs替换这些异常值。 我稍微修改了此处提供的函数:。尝试向量函数时效果很好,但我的问题是在数据帧上使用它。该函数检测异常值,但我不知道如何将结果作为数据帧 因此,我想要的是将原始数据帧替换为R 使用索引替换df中的值,r,outliers,R,Outliers,我正在尝试检测数据帧中的异常值,并用NAs替换这些异常值。 我稍微修改了此处提供的函数:。尝试向量函数时效果很好,但我的问题是在数据帧上使用它。该函数检测异常值,但我不知道如何将结果作为数据帧 因此,我想要的是将原始数据帧替换为NAs。其中NA将是检测到的异常值 这是我迄今为止一直尝试的: library(outliers) data("rock") # Function to detect outliers with Grubbs test in a vector grubbs.flag &
NA
s。其中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)
}
库(异常值)
数据(“岩石”)
#函数用于检测向量中的Grubbs测试异常值
grubbs.flag您应该在while循环之前添加以下内容:
na.vect <- test
第二个参数2指示将其应用于数据帧的列。行使用1。您应该在while循环之前添加:
na.vect <- test
第二个参数2指示将其应用于数据帧的列。行使用1。我想这与脚本末尾的apply和as.vector有关。我将在我的笔记本电脑上运行它,并为您查看发生了什么。我想这与脚本末尾的apply和as.vector有关。我会在我的笔记本电脑上运行,帮你看看发生了什么。