我正在尝试从包含x
和y
变量的数据框中删除离群值,这些变量根据变量cond
进行分组。
我创建了一个基于箱线图统计数据的函数来删除离群值,并返回没有离群值的df
。当应用于原始数据时,该函数表现良好。然而,如果应用于分组数据,则函数无法正常工作,并且会返回一个错误:
Error in mutate_impl(.data, dots) :
Evaluation error: argument "df" is missing, with no default.
请问,我应该如何修改这个函数,使其接受向量
df$x
和 df$y
作为参数,并正确地按组去除离群值?
我的虚拟数据:
set.seed(955)
# Make some noisily increasing data
dat <- data.frame(cond = rep(c("A", "B"), each = 22),
xvar = c(1:10+rnorm(20,sd=3), 40, 10, 11:20+rnorm(20,sd=3), 85, 115),
yvar = c(1:10+rnorm(20,sd=3), 200, 60, 11:20+rnorm(20,sd=3), 35, 200))
removeOutliers<-function(df, ...) {
# first, identify the outliers and store them in a vector
outliers.x<-boxplot.stats(df$x)$out
outliers.y<-boxplot.stats(df$y)$out
# remove the outliers from the original data
df<-df[-which(df$x %in% outliers.x),]
df[-which(df$y %in% outliers.y),]
}
# REmove outliers (try if function works)
removeOutliers(dat)
# Apply the function to group
# Not working!!!
dat_noOutliers<- dat %>%
group_by(cond) %>%
mutate(removeOutliers)
我找到了一个函数,可以用来从向量数据中移除异常值。然而,我想从数据框中的df$x
和df$y
向量中移除异常值。
remove_outliers <- function(x, na.rm = TRUE, ...) {
qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...)
H <- 1.5 * IQR(x, na.rm = na.rm)
y <- x
y[x < (qnt[1] - H)] <- NA
y[x > (qnt[2] + H)] <- NA
y
}
mutate
的初学者,但我会记住这个 :) 谢谢! - maycca