YefR
YefR

Reputation: 369

How to create new vector based on a certain value in another vector?

I have the following code:

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

Now, I want to create a new variable that is based for each participant on the "my decs" value in the last round, which is always 6.
I want the new variable to be the value of "my_decs" in the last round: so the final output should be:

         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

How can I do it?

Upvotes: 1

Views: 215

Answers (2)

Grzegorz Sionkowski
Grzegorz Sionkowski

Reputation: 529

Consider using 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

Upvotes: 2

GordonShumway
GordonShumway

Reputation: 2056

Using the tidyverse package:

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

Upvotes: 2

Related Questions