将块添加到R数据

时间:2016-05-14 19:50:14

标签: r vector split

我有以下数据

set.seed(1234)
round<-rep(1:12,2)
players<-rep(1:2, c(12,12))
decs<-sample(1:3,24,replace=TRUE)
game<-rep(rep(1:2,c(6,6)),2)
gamematrix<-cbind(players,game,round,decs)
gamematrix

        players game round decs
 [1,]       1    1     1    1
 [2,]       1    1     2    2
 [3,]       1    1     3    2
 [4,]       1    1     4    2
 [5,]       1    1     5    3
 [6,]       1    1     6    2
 [7,]       1    2     7    1
 [8,]       1    2     8    1
 [9,]       1    2     9    2
[10,]       1    2    10    2
[11,]       1    2    11    3
[12,]       1    2    12    2
...

现在,我想添加一个列:“阻止”,这样对于每个游戏中的每个玩家,前3轮将是第1轮,接下来的第3轮将是第2轮。

上述数据的结果应为:

       players game round decs block
 [1,]       1    1     1    1    1
 [2,]       1    1     2    2    1
 [3,]       1    1     3    2    1
 [4,]       1    1     4    2    2
 [5,]       1    1     5    3    2
 [6,]       1    1     6    2    2    
 ...

任何想法怎么做?   谢谢!

1 个答案:

答案 0 :(得分:1)

我们可以使用ave

cbind(gamematrix, block =ave((gamematrix[,3]-1)%%3==0, 
                      gamematrix[,1], gamematrix[,2], FUN= cumsum))
#      players game round decs block
# [1,]       1    1     1    1     1
# [2,]       1    1     2    2     1
# [3,]       1    1     3    2     1
# [4,]       1    1     4    2     2
# [5,]       1    1     5    3     2
# [6,]       1    1     6    2     2
# [7,]       1    2     7    1     1
# [8,]       1    2     8    1     1
# [9,]       1    2     9    2     1
#[10,]       1    2    10    2     2
#[11,]       1    2    11    3     2
#[12,]       1    2    12    2     2
#[13,]       2    1     1    1     1
#[14,]       2    1     2    3     1
#[15,]       2    1     3    1     1
#[16,]       2    1     4    3     2
#[17,]       2    1     5    1     2
#[18,]       2    1     6    1     2
#[19,]       2    2     7    1     1
#[20,]       2    2     8    1     1
#[21,]       2    2     9    1     1
#[22,]       2    2    10    1     2
#[23,]       2    2    11    1     2
#[24,]       2    2    12    1     2