添加基于先前向量的向量

时间:2016-05-13 19:10:45

标签: r vector

以下是我的数据:

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
 [1,]       1    1     1    2
 [2,]       1    1     2    2
 [3,]       1    1     3    1
 [4,]       1    1     4    2
 [5,]       1    1     5    1
 [6,]       1    2     1    1
 [7,]       1    2     2    1
 [8,]       1    2     3    2
 [9,]       1    2     4    1
[10,]       1    2     5    3
[11,]       2    1     1    2
[12,]       2    1     2    1
[13,]       2    1     3    3
[14,]       2    1     4    3
[15,]       2    1     5    3
[16,]       2    2     1    3
[17,]       2    2     2    2
[18,]       2    2     3    1
[19,]       2    2     4    1
[20,]       2    2     5    2 

现在,我想添加另一个专栏:&#34; Same Choice&#34;我希望成为&#34; 1&#34;如果同一游戏中的同一玩家在下一轮做出与上一回合相同的决定。例如,对于播放器1,输出应为:c(0,1,0,0,0,0,1,0,0,0)。任何想法我该怎么办?

谢谢!

2 个答案:

答案 0 :(得分:2)

以下是data.table答案:

# set seed
set.seed(1234)

# load data
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)

library(data.table)
dt <- data.table(gamematrix)
dt[, .(decs=decs, lag=c(0,head(decs,-1)), 
                  sameDec=as.integer(decs==c(NA,head(decs,-1)))),
   by=c("players","game")]

我包含了滞后期限,以便您可以验证。

@Frank建议使用shift更清洁(可能更快):

dt[, .(decs=decs, lag=shift(decs, 1), 
                  sameDec=as.integer(decs==shift(decs, 1))),
by=c("players","game")]

与我的手动编码滞后相比。

答案 1 :(得分:0)

以下代码可以使用

library(dplyr)
gamematrix %>% as.data.frame %>% group_by(players, game) %>% mutate(new_col = ifelse(decs == lag(decs), 1, 0) )
gamematrix$new_col[is.na(gamematrix$new_col)]<- 0