3
根据组变量,我试图使用by
函数来替换数据帧中多个变量的异常值。 以下是我的努力。但是,我收到一个错误。替换每个组的异常值
# R code:
library(tidyverse)
library(dplyr)
# outlier function definition
my_outlier <- function(x){
stats <- boxplot.stats(unlist(x))
outlier <- stats$out
outlier_idx <- which(unlist(x) %in% outlier)
max <- max(x[-outlier_idx]); min <- min(x[-outlier_idx])
x <- ifelse(x>max, max,ifelse(x < min, min, x))
return(x)
}
# use the above defined func to substitue outliers of 1 variable in a dataframe, according to a Group variable.
group_data <- as_tibble(data.frame(x=c(runif(10),2.5,-2.3,runif(10,1,2),3.5,-1.5), group=c(rep(1,12),rep(2,12))))
View(group_data)
by(group_data$x, group_data$group, my_outlier, simplify=FALSE)
# use the above defined func to substitue outliers of 1+ variable in a dataframe, according to a Group variable.
group_datas <- as_tibble(data.frame(x=c(runif(10),2.5,-2.3,runif(10,1,2),3.5,-1.5),
y=c(runif(10,2,3),4,-1,runif(10,3,4),6,-1),
group=c(rep(1,12),rep(2,12))))
by(group_data[,1:2], group_data$group, my_outlier)
当使用我定义的函数根据组变量取代数据框中1+变量的异常值时,出现错误。
我不知道我的代码的哪一部分导致了错误。
你缺少列索引,你要计算的列max'中的最大值 - (max [-outlier_idx]); min < - min(x [-outlier_idx])'。如果你想考虑整个矩阵,包括组列,你需要在'outlier_idx'后添加逗号作为'max < - max(x [-outlier_idx,]); min < - min(x [-outlier_idx,])'。还要注意'ifelse'只返回标量而不是向量。 – discipulus