如何根据另一个向量中的某个值创建新向量?

问题描述 投票:1回答:2

我有以下代码:

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

我该怎么做?

r data-manipulation
2个回答
2
投票

使用tidyverse包:

library(tidyverse)
gamematrix %>% 
  as.data.frame() %>% 
  group_by(players) %>% 
  mutate(new_var = tail(my_decs, 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
© www.soinside.com 2019 - 2024. All rights reserved.