计算不同值

时间:2018-04-11 20:25:29

标签: r

我有以下数据:

set.seed(5)
round<-rep(1:5,4)
players<-rep(1:2, c(10,10))
decs<-sample(1:3,20,replace=TRUE)
game<-rep(rep(1:2,c(5,5)),2)
gamematrix<-cbind(players,game,round,decs)
gamematrix



        players game round decs **decs1_sum**    **decs2_sum** **decs3_sum**
 [1,]       1    1     1    1       3                  0              2
 [2,]       1    1     2    3       3                  0              2
 [3,]       1    1     3    3       3                  0              2 
 [4,]       1    1     4    1       3                  0              2
 [5,]       1    1     5    1       2                  0              2 
 [6,]       1    2     1    3       2                  1              3
 [7,]       1    2     2    2       2                  1              3
 [8,]       1    2     3    3       2                  1              3
 [9,]       1    2     4    3       2                  1              3
[10,]       1    2     5    1       2                  1              3 
[11,]       2    1     1    1       3                  2              0 
[12,]       2    1     2    2       3                  2              0
[13,]       2    1     3    1       3                  2              0 
[14,]       2    1     4    2       3                  2              0
[15,]       2    1     5    1       3                  2              0
[16,]       2    2     1    1       1                  2              2
[17,]       2    2     2    2       1                  2              2 
[18,]       2    2     3    3       1                  2              2 
[19,]       2    2     4    2       1                  2              2 
[20,]       2    2     5    3       1                  2              2

现在我想创建以下三个变量:decs1_sum,decs2_sum,decs3_sum,它们为每个游戏中的每个玩家的每个决策的出现次数求和。所以输出应该如上所述..

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

使用tidyverse套件包:

game_summary <- gamematrix %>%
  data.frame %>%
  group_by(players, game) %>%
  summarize(
    decs1_sum = sum(decs == 1),
    decs2_sum = sum(decs == 2),
    decs3_sum = sum(decs == 3)
 )
gamematrix <- gamematrix %>% 
  data.frame %>%
  left_join(game_summary, by = c("players", "game"))

如果您不熟悉管道操作符(%>%),它只需将最后一个函数的结果作为下一个函数的第一个元素输入,这样可以更容易地查看数据的方式帧在每一步都被修改。