I have a question regarding Rock, Paper, Scissors, Lizard, Spock game. I have the following code
dataTable <- matrix(data = NA, nrow = 25, ncol = 3, byrow = TRUE)
dataTable <- as.data.frame(dataTable)
colnames(dataTable) <- c("Player-1", "Player-2", "Outcome")
## Fill in columns
dataTable[, 1] <- c(rep("Rock", 5), rep("Paper", 5), rep("Scissors", 5),
rep("Lizard", 5), rep("Spock", 5))
dataTable[, 2] <- c(rep(c("Rock", "Paper", "Scissors", "Lizard", "Spock"), 5))
# Filling In The Outcome Column:
outcome_col <- c("Draw!", "Player 2 Wins!", "Player 1 Wins!", "Player 1 Wins!", "Player 2 Wins!",
"Player 1 Wins!", "Draw!", "Player 2 Wins!", "Player 2 Wins!", "Player 1 Wins!",
"Player 2 Wins!", "Player 1 Wins!", "Draw!", "Player 1 Wins!", "Player 2 Wins!",
"Player 2 Wins!", "Player 1 Wins!", "Player 2 Wins!", "Draw!", "Player 1 Wins!",
"Player 1 Wins!", "Player 2 Wins!", "Player 1 Wins!", "Player 2 Wins!", "Draw!")
# Place outcome_col as third column and convert as factors:
dataTable[, 3] <- as.factor(outcome_col)
sheldon_game<-function(A,B){
for (i in 1:nrow(dataTable)){
if (A!=dataTable[i,1] & B!=dataTable[i,2]){
stop("Parameters out of bound")
} else
if (A==dataTable[i,1] & B==dataTable[i,2]){
res<-dataTable[i,3]
}
}
return(res)
}
sheldon_game("Scissors","Paper")
In the last function sheldon_game, i want to print error message if other than (Rock, Paper, Scissors, Lizard, Spock) inserted. But it continously shows the results as error message evn the parameters are within the list.
CodePudding user response:
The problem is you are testing to see if there is a match on each row and since the input data will match only one row, you always get the error message. Your code can be modified as follows:
sheldon_game<-function(A,B){
for (i in 1:nrow(dataTable)){
if (! A %in% unique(dataTable[ ,1]) | ! B %in% unique(dataTable[ ,2])){
stop("Parameters out of bound")
} else
if (A==dataTable[i,1] & B==dataTable[i,2]){
res<-dataTable[i,3]
}
}
return(as.character(res))
}
This will check to make sure that the values are included, but there would be simpler ways to do this. The modification to the return
line keeps R from listing the factor levels.
For reference, this would take advantage of vectorization in R:
sheldon_game<-function(A, B) {
Avals <- unique(dataTable[, 1])
Bvals <- unique(dataTable[, 2])
if(A %in% Avals & B %in% Bvals) {
idx <- which(A==dataTable[, 1] & B==dataTable[, 2])
return(as.character(dataTable[idx, 3]))
} else return("Parameters out of bound!")
}