如何基于另一个向量中的某个值创建新向量?

时间:2019-04-09 21:41:39

标签: r data-manipulation

我有以下代码:

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

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

现在,我想创建一个新变量,该变量基于上一轮的“ my decs”值(始终为6)为每个参与者提供。
我希望新变量在上一轮是“ my_decs”的值:因此最终输出应为:

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

我该怎么办?

2 个答案:

答案 0 :(得分:2)

使用tidyverse软件包:

library(tidyverse)
gamematrix %>% 
  as.data.frame() %>% 
  group_by(players) %>% 
  mutate(new_var = tail(my_decs, 1))

答案 1 :(得分:2)

考虑使用data.table:

library(data.table)
gamematrix <- as.data.table(gamematrix)
gamematrix[,new_var:=max(my_decs),by=players]
    players game round decs my_decs new_var
 1:       1    1     1    2       0       4
 2:       1    1     2    3       0       4
 3:       1    1     3    1       0       4
 4:       1    2     4    2       0       4
 5:       1    2     5    3       0       4
 6:       1    2     6    3       4       4
 7:       2    1     1    3       0       9
 8:       2    1     2    3       0       9
 9:       2    1     3    2       0       9
10:       2    2     4    1       0       9
11:       2    2     5    2       0       9
12:       2    2     6    3       9       9