2015-01-11 50 views
0

我希望有人可以帮助您找到用于使用错误条生成条形图的shotcut。一般来说,我喜欢这样做更简单的方法来用SE来绘制条形图

# some dummy data 
q <- setNames(data.frame(matrix(sample(100,400,T), nrow=20)), 
c("A","B","C","D","E","F","G","H","I","G","K","L","M","O","P","Q","R","S","T","U")) 

#I usually melt the data 
library(reshape2) 
a1 <- melt(q) 

# summarize them 
library(plyr) 
a2 <- ddply(a1, c("variable"), summarise, mvalue = mean(value, na.rm=TRUE), 
              medvalue = median(value, na.rm=TRUE), 
              sd = sd(value, na.rm=TRUE),  
              n = sum(!is.na(value)),se = sd/sqrt(n)) 

#However, I got an error in generating se: 
#Error in sd/sqrt(n) : non-numeric argument to binary operator 

# then I plot the graph 
library(ggplot2) 
ggplot(sum1, aes(x=variable, y=mvalue, fill=variable))+ 
geom_bar(stat='identity', position='dodge')+ 
geom_errorbar(aes(ymin=mvalue-sd,ymax=mvalue+sd))+ 
scale_fill_grey() 
# here i used the sd instead of se 

为什么我得到了se的错误?有什么办法可以保存所有这些步骤来以更智能的方式生成带有错误栏的条形图?

+1

阴影之前,我从来没有使用过'plyr'但是这有什么错只需使用'从基础R aggregate'?下面看起来似乎起作用:汇总(value_variable,a1,function(x)c(mean = mean(x,na.rm = TRUE), medvalue = median(x,na.rm = TRUE), sd = sd(x,na.rm = TRUE), se = sd(x,na.rm = TRUE)/ sqrt(sum(!is.na(x)))))' –

+0

谢谢,大卫,你能告诉我怎么做使用ggplot绘制数据? – Samehmagd

+0

你的代码不适用于生成的'se'? –

回答

1

ddply几乎完全停止活动在dplyr

library(dplyr) 
a1$variable <- as.character(a1$variable) 
a1 %>% 
    group_by(variable) %>% 
    summarise(mvalue = mean(value, na.rm=TRUE), 
      medvalue = median(value, na.rm=TRUE), 
      sd = sd(value, na.rm=TRUE),  
      n = sum(!is.na(value)), se = sd/sqrt(n)) %>% 
    ggplot(., aes(x=variable, y=mvalue, fill=variable)) + 
    geom_bar(stat='identity', position='dodge')+ 
    geom_errorbar(aes(ymin=mvalue-se, ymax=mvalue+se))+ 
    scale_fill_grey() 
+0

找到一些方法来手动添加SE列使用q3 <-cbind(se = q2 $ sd/sqrt(q2 $ n),q2)。仍然在寻找更简单的方式来绘制图表, – Samehmagd

+0

令人惊讶的是,重新安装R和Rstudio解决了这个问题! – Samehmagd

相关问题