J'essaie d'utiliser la fonction by
pour substituer des valeurs aberrantes de nombreuses variables dans une trame, en fonction d'une variable de groupe. Les suivants sont mes efforts. Mais, j'ai une erreur.Substitutions aberrantes pour chaque groupe
# 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)
lorsque vous utilisez ma fonction définie pour les valeurs aberrantes de 1+, substituer variable dans une trame de données, selon une variable du groupe, je me suis une erreur.
Je ne sais pas quelle partie de mon code a provoqué l'erreur.
Il vous manque un index de colonne, quelle colonne vous voulez calculer le maximum de 'max <- max (x [-outlier_idx]); min <- min (x [-outlier_idx]) '. Si vous voulez considérer une matrice entière incluant la colonne de groupe, vous devez ajouter une virgule après 'outlier_idx' comme' max <- max (x [-outlier_idx,]); min <- min (x [-outlier_idx,]) '. Notez également que 'ifelse' renvoie uniquement les scalaires et non les vecteurs. – discipulus