查找“组之间”的平方和

时间:2018-11-08 02:11:08

标签: r for-loop dataframe statistics

我有一些看起来像这样的数据:

 October    November   Setting
 1           3.1        1
 1.3         1.2        2
 2.1         .7         1
 .8          .1         2

我想做的是创建一个for循环,以解决组之间的平方和。

基本上我想要的是这/这是我正在考虑的一些短代码。这不是很有效。

 month.sum = 0
 for i in Setting {
      month.sum <- month.sum + (group.mean(i) + grand.mean)^2
  }

我想从根本上找到它,作为直接翻译:

 (group mean(when the setting=1) + grand mean)^2 + (group mean(when the setting=2) + grand mean)^2

我已经解决了重大问题,只是致力于我的循环能力。谢谢!

1 个答案:

答案 0 :(得分:0)

> df_result
# A tibble: 8 x 6
# Groups:   Setting [2]
  Setting Month    Value grand.mean group.mean month.sum
    <int> <chr>    <dbl>      <dbl>      <dbl>     <dbl>
1       1 October    1         1.29       1.72      9.08
2       2 October    1.3       1.29       0.85      4.57
3       1 October    2.1       1.29       1.72     36.3 
4       2 October    0.8       1.29       0.85     18.3 
5       1 November   3.1       1.29       1.72     81.7 
6       2 November   1.2       1.29       0.85     41.1 
7       1 November   0.7       1.29       1.72    145.  
8       2 November   0.1       1.29       0.85     73.1 

代码

df_result <- df %>%
    gather("Month", "Value", -Setting) %>%
    mutate(grand.mean = mean(Value)) %>%
    group_by(Setting) %>%
    mutate(group.mean = mean(Value)) %>%
    mutate(month.sum = cumsum(group.mean + grand.mean)^2)

数据

df <- read.table(text = "October    November   Setting
1           3.1        1
1.3         1.2        2
2.1         .7         1
.8          .1         2", header = TRUE)