R中均值组的均值

Mean of Groups of means in R

我有以下数据

Exp = 我的数据框

dt<-data.table(Game=c(rep(1,9),rep(2,3)),
               Round=rep(1:3,4),
               Participant=rep(1:4,each=3),
               Left_Choice=c(1,0,0,1,1,0,0,0,1,1,1,1),
               Total_Points=c(5,15,12,16,83,7,4,8,23,6,9,14))

> dt
    Game Round Participant Left_Choice Total_Points
 1:    1     1           1           1            5
 2:    1     2           1           0           15
 3:    1     3           1           0           12
 4:    1     1           2           1           16
 5:    1     2           2           1           83
 6:    1     3           2           0            7
 7:    1     1           3           0            4
 8:    1     2           3           0            8
 9:    1     3           3           1           23
10:    2     1           4           1            6
11:    2     2           4           1            9
12:    2     3           4           1           14

现在,我需要执行以下操作:

  1. 首先,我需要为每场比赛的每位参与者计算平均值 "Left Choice rate"。

  2. 之后我想把结果分成5组(左选<20%, 在 20% 和 40% 之间左选择 e.t.c),

  3. 对于每个组(在每场比赛中),我想计算最后一轮 Total_Points 的 mean ** - 这个简单示例中的第 3 轮 **** [只有第 3 轮的值] - 例如,对于参与者 1,在第 1 场比赛中,第 3 轮的总分是 12。对于参与者 4,在第 2 场比赛中它是 14。

所以在第一阶段我想我应该计算如下:

Game Participant Percent_left    Total_Points (in last round) 

1        1           33%            12
1        2           66%            7 
1        3           33%            23   
2        4           100%           14

最终结果应该是这样的:

Game  Left_Choice Total_Poins (average)    
    1         >35%                   17.5= (12+23)/2
    1     <35%<70%                   7
    1         >70%                   NA
    2         >35%                   NA
    2     <35%<70%                   NA
    2         >70%                   14 

请帮忙! :)

data.table

工作

1:简单组均值 by

dt[,pct_left:=mean(Left_Choice),by=.(Game,Participant)]

2:使用cut;不是很清楚,但我想你想要 include.lowest=T.

dt[,pct_grp:=cut(pct_left,breaks=seq(0,1,by=.2),include.lowest=T)]

3:稍微复杂的组均值 by

dt[Round==max(Round),end_mean:=mean(Total_Points),by=.(pct_grp,Game)]

(如果您只想减少 table,请改用 .(end_mean=mean(Total_Points)))。

你没有说清楚是否有全局最大回合数(即是否所有游戏都以相同的回合数结束);这是上面假设的。为了提供一个确切的替代方案,你必须对此更加清楚,但我建议从逐轮定义它开始:

dt[,end_mean:=mean(Total_Points),by=.(pct_grp,Game,Round)]