代码之家  ›  专栏  ›  技术社区  ›  tjebo

统计摘要:将单个观测值纳入聚合函数

  •  0
  • tjebo  · 技术社区  · 8 年前

    我想“强制”统计摘要中的聚合函数来计算单个观测的输出值:

    set.seed(1)
    值<-c(代表(1:6,每个=3),7:8)
    rel_freq<-样本(x=序列(0,1,0.1),大小=长度(值),替换=真)
    示例df<-data.frame(值,rel_freq)
    
    需要(ggplot2)
    ggplot()图+
    统计摘要(数据=示例数据,
    映射=aes(x=as.character(value),y=rel_freq)
    fun.data=平均值
    
    #警告消息:删除了两行,其中包含缺少的值(geom_pointrange)
    

    现在这里发生了什么(IMO)是因为ggplotremoved observations 7 and 8 because the aggregating function instat_summarydoes not work with single observations?但是这里有强制输出的方法吗?set.seed(1) value <- c(rep(1:6, each = 3), 7:8) rel_freq <- sample(x = seq(0, 1, 0.1), size = length(value), replace = TRUE) example_df <- data.frame(value, rel_freq) require(ggplot2) ggplot() + stat_summary(data = example_df, mapping = aes(x = as.character(value), y = rel_freq), fun.data = mean_se) # Warning message: Removed 2 rows containing missing values (geom_pointrange)

    现在这里发生的是ggplot删除了观察值7和8,因为stat_summary不适用于单次观察?但是这里有强制输出的方法吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   markus    8 年前

    您可以编写自己的小函数来扩展x的长度等于1的情况。 mean_se

    mean_se_tjebo<-函数(x,mult=1){
    x<-状态::na.omit(x)
    SE<-mult*sqrt(状态::var(x)/长度(x))
    平均值<-平均值(x)
    如果(长度(x)!= 1){
    data.frame(y=平均值,ymin=平均值-se,ymax=平均值+se)
    }其他{
    data.frame(y=平均值,ymin=平均值,ymax=平均值)
    }
    }
    

    现在的情节如下

    ggplot()。+
    统计摘要(数据=示例数据,
    映射=aes(x=as.character(value),y=rel_freq)
    fun.data=平均值
    
    
    

    现在的情节如下

    ggplot() + 
      stat_summary(data = example_df,
                   mapping = aes(x = as.character(value), y = rel_freq),
                   fun.data = mean_se_tjebo)
    

    enter image description here