我有一個關于 Rock, Paper, Scissors, Lizard, Spock 游戲的問題。我有以下代碼
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 中,如果插入的不是(巖石、紙、剪刀、蜥蜴、史波克),我想列印錯誤訊息。但是即使引數在串列中,它也會不斷地將結果顯示為錯誤訊息。
uj5u.com熱心網友回復:
問題是您正在測驗以查看每一行是否匹配,并且由于輸入資料將僅匹配一行,因此您總是會收到錯誤訊息。您的代碼可以修改如下:
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!")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316359.html
上一篇:PHP在類if陳述句中宣告方法
