【发布时间】:2019-07-21 19:52:32
【问题描述】:
我正在研究 RStudio,试图遍历几行 dplyr-ggplot 脚本来识别异常值,然后绘制一个图并标记异常值。数据的子集如下所示:
miR_373 miR_30 miR_182 type
C1 6.78 -2.88 3.75 control
C2 11.88 0.28 7.26 control
C3 8.55 -4.08 3.37 control
C4 7.60 -2.76 7.60 control
C5 13.18 2.33 13.18 control
P18 12.62 0.37 7.99 treated
P19 4.60 -7.62 -0.52 treated
P23 9.72 0.07 9.72 treated
P24 10.40 -0.68 10.40 treated
P25 11.08 0.81 11.08 treated
N20 7.35 -4.29 2.48 non_treated
N21 3.06 -2.21 4.59 non_treated
N22 6.05 -4.99 2.15 non_treated
N28 10.44 -0.15 10.44 non_treated
N29 10.59 0.36 10.59 non_treated
以下脚本可以很好地生成一个情节:
cts <- as.data.frame(read.csv("c:/Users/dat.csv", header = TRUE, row.names = 1))
is_outlier <- function(x) {
return(x< quantile(x,0.25) - 1.5 * IQR(x) | x>quantile(x,0.75) +1.5 * IQR(x))
}
dat <- cts %>% tibble::rownames_to_column(var="outlier") %>% group_by(type) %>% mutate(is_outlier=ifelse(is_outlier(miR_373), miR_373, as.numeric(NA)))
dat$outlier[which(is.na(dat$is_outlier))] <- as.numeric(NA)
ggplot(dat, aes(y=miR_373, x=factor(type))) + geom_boxplot() + geom_text(aes(label=outlier),na.rm=TRUE,hjust=0.05) + geom_dotplot(binaxis='y', stackdir='center', dotsize=1, binwidth = .5)
生产
但是下面的代码不能循环遍历变量(列):
miRs <- names(cts)[c(1,2,3)]
for(i in miRs){
dat2 <- cts %>% tibble::rownames_to_column(var="outlier") %>% group_by(type) %>% mutate(is_outlier=ifelse(is_outlier(i), i, as.numeric(NA)))
dat2$outlier[which(is.na(dat2$is_outlier))] <- as.numeric(NA)
ggplot(dat2, aes(y=i, x=factor(type))) + geom_boxplot() + geom_text(aes(label=outlier),na.rm=TRUE,hjust=0.05) + geom_dotplot(binaxis='y', stackdir='center', dotsize=1, binwidth = .5)
}
Error in mutate_impl(.data, dots) : Evaluation error: non-numeric argument to binary operator.
我可以说我在循环中替换 i 不被接受,但我不知道为什么,也没有找到另一种方法来做到这一点。任何建议或进一步阅读将不胜感激。
【问题讨论】:
-
我认为使用
purrr包是遍历列表、向量或列的最佳方式。