【问题标题】:Loop over subsets in frame with customised variance function使用自定义方差函数循环帧中的子集
【发布时间】:2021-03-17 08:58:24
【问题描述】:

数据框结构:

id_group <- c(a,a,a,b,b,b,c,c,c,d,d,d)
group_mean <- c(3,3,3,4,4,4,2,2,2,3,3,3)
value <- c(2,3,3,4,2,2,4,4,3,2,2,3)
df <- data.frame(id_group, group_mean, value)

我是 r 的新手,我正在尝试根据在 stackoverflow 上搜索到的许多答案拼凑适当的代码。 我试图确定给定平均值的每个组(group_id)的方差 - 因此我不能只使用 var()。相反,我正在为方差创建一个自定义函数。

如何组合我拥有的两个代码(一个用于循环,一个用于方差计算)

方差:

x = df$value 
variance <- function(x){
  x = as.numeric(x)
  x = na.omit(x)
  m = mean(x)
  return(
    sum((x-m)^2, na.rm = TRUE)/(length(x) - 1)
  )
}

循环:

uniq <- unique(unlist(df$group_id))
for (i in 1:length(uniq)){
data_1 <- subset(df, group_id == uniq[i])
#insert function}

非常感谢任何帮助。

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以使用aggregate/tapply 为每个id_group 应用variance

    aggregate(value~id_group, df, variance)
    

    您可以在dplyr 关注:

    library(dplyr)
    df %>% group_by(id_group) %>% summarise(variance = variance(value))
    
    #  id_group variance
    #* <chr>       <dbl>
    #1 a           0.333
    #2 b           1.33 
    #3 c           0.333
    #4 d           0.333
    

    【讨论】:

      【解决方案2】:

      我们可以使用collapse

      library(collapse)
      library(magrittr)
      df %>%
         fgroup_by(id_group) %>%
         fsummarise(variance = fvar(value))
      

      -输出

      #  id_group  variance
      #1        a 0.3333333
      #2        b 1.3333333
      #3        c 0.3333333
      #4        d 0.3333333
      

      数据

      df <- structure(list(id_group = c("a", "a", "a", "b", "b", "b", "c", 
      "c", "c", "d", "d", "d"), group_mean = c(3, 3, 3, 4, 4, 4, 2, 
      2, 2, 3, 3, 3), value = c(2, 3, 3, 4, 2, 2, 4, 4, 3, 2, 2, 3)),
      class = "data.frame", row.names = c(NA, 
      -12L))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-23
        • 2020-04-03
        • 2017-03-02
        相关资源
        最近更新 更多