I have a data set named "dat".
TEAM1 TEAM2 WINNER
A P A
I S I
P S S
S I I
S P P
W P W
A E A
A S S
E A E
I want to create variable "LOSER" using R code. I have tried like this
Loser <- NULL
for (i in 1: nrow(dat)){
if(match(dat$Team1[i],dat$Winner)==TRUE){
Loser[i] <- cricket$Team2[i]
}else if(match(dat$Team1[i],dat$Winner)==FALSE ){
Loser[i] <- dat$Team1[i]
}
}
But this does not give exact result. What is wrong with this code?
Desired out put:
TEAM1 TEAM2 WINNER LOSER
A P A P
I S I S
P S S P
S I I S
S P P S
W P W P
A E A E
A S S A
E A E A
dat[1:2][cbind(1:nrow(dat),with(dat, TEAM1==WINNER)+1L)]