lundi 18 juillet 2016

Adding variable in R based on condition

I have the following game:

set.seed(1234)
round<-rep(1:20)
players<-rep(1, c(10))
game<-rep(rep(1:2,c(10,10)))
gamematrix<-cbind(players,game,round)
gamematrix1<-data.frame(gamematrix)

Which gives the following output:

       players game round
 [1,]       1    1     1
 [2,]       1    1     2
 [3,]       1    1     3
 [4,]       1    1     4
 [5,]       1    1     5
 [6,]       1    1     6
 [7,]       1    1     7
 [8,]       1    1     8
 [9,]       1    1     9
[10,]       1    1    10
[11,]       1    2    11
[12,]       1    2    12
[13,]       1    2    13
[14,]       1    2    14
[15,]       1    2    15
[16,]       1    2    16
[17,]       1    2    17
[18,]       1    2    18
[19,]       1    2    19
[20,]       1    2    20

I would like to add a variable: first8 that is assigned a value of 1 if it is the first 8 rounds in each of the games and 0 otherwise.

So I would like to add something like:

if (gamematrix1$round<8 || gamematrix1$round>10 && gamematrix1$round <18){
    gamematrix1$first8<-1
} else {
   gamematrix1$first8<-0
}

I know that this code is not working, and that I need to add a loop to make it working. But is there a more elegant way?

Aucun commentaire:

Enregistrer un commentaire