2017-02-13 3 views
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+の外れ値をsubstitueために私の定義された機能を使用する場合、グループの変数によると、私はエラーを得ました。

私のコードのどの部分がエラーを引き起こしたのか分かりません。

boxplot.statsが動作しません、あなたはパッケージ outliersから outlierテストを使用することができ、多変量外れ値のために
+0

あなたが計算したいん列の列インデックスを、欠けています'max < - max(x [-outlier_idx])の最大値。 min < - min(x [ - outlier_idx]) 'となる。グループ列を含む行列全体を考慮する場合は、 'outlier_idx'の後にカンマを' max < - max(x [-outlier_idx、]);と追加する必要があります。 min < - min(x [ - outlier_idx、]) 'となります。 'ifelse'はベクトルではなくスカラーだけを返します。 – discipulus

答えて

1

、:

library(outliers) 
my_outlier2 <- function(x, plot=TRUE){ 
    x <- as.matrix(x) 
    outlier <- rbind(outlier(x),outlier(x,opposite=TRUE)) 
    outlier_idx <- which(duplicated(rbind(x, outlier), fromLast=TRUE))#which(apply(mapply(x, outlier, FUN="=="), MARGIN=1, FUN=all)) 
    if (plot) { # if 2-D data, visualize 
    plot(x[,1], x[,2], pch=19, xlab='x', ylab='y') 
    points(x[outlier_idx,1], x[outlier_idx,2], col='red', pch=8, cex=2) 
    legend('topleft', legend=c('non-outlier', 'outlier'), pch=c(19, 8), col=c('black', 'red')) 
    } 
    x <- x[-outlier_idx,] 
    return(x) 
} 

# 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_datas[,1:2], group_datas$group, my_outlier2) 

enter image description here

関連する問題