r语言 - if else停止条件



我有一个关于石头剪刀布蜥蜴史波克游戏的问题。我有以下代码

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")

在最后一个函数sheldon_game中,我想打印除(石头,布,剪刀,蜥蜴,史波克)插入之外的错误消息。但是,即使参数在列表中,它也会不断地将结果显示为错误消息。

问题是您正在测试是否在每一行上都有匹配,并且由于输入数据将只匹配一行,因此您总是得到错误消息。您的代码可以修改如下:

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))
}

这将检查以确保包含值,但有更简单的方法可以做到这一点。对return行的修改使R无法列出因子水平。

作为参考,这将利用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!")
}

最新更新