如果包含if
語句來控制readinteger
函數中的打印,這將工作正常。這樣,readline
將按預期運行(等待來自用戶的輸入),然後自動轉到打印命令。
readinteger <- function()
{
n <- readline(prompt="Enter your location: ")
n <- as.integer(n)
x <- "You are at location one."
y <- "You are at location two."
z <- "You are lost."
if (n == 1)
{
print(x)
}
else if (n == 2)
{
print(y)
}
else
print(z)
}
readinteger()
你在你的代碼,並沒有做任何事情有一個if (is.na(n))
,但我的猜測是要包括檢查,以確保用戶提供有效的輸入。如果是這樣,您可能會發現while
循環有幫助,因此如果出現錯誤,用戶可以更正它們的輸入。例如:
readinteger <- function()
{
n <- NULL
while(!is.integer(n)){
n <- readline(prompt="Enter your location: ")
n <- try(suppressWarnings(as.integer(n)))
if(is.na(n)) {
n <- NULL
message("\nYou must enter an integer. Please try again.")
}
}
x <- "You are at location one."
y <- "You are at location two."
z <- "You are lost."
if (n == 1)
{
print(x)
}
else if (n == 2)
{
print(y)
}
else
print(z)
}
readinteger()
是這樣的? 'readinteger < - function(){n < - readline(prompt =「輸入您的位置:」); n < - as.integer(n); if(is.na(n))return(as.integer(n)); ifelse(n == 1,「代碼爲1」,「代碼爲2」)} ' – Jimbou
@Jimbou:您的代碼有效,但它需要分號,因爲註釋區域已刪除換行符。 'readinteger < - function(){n < - readline(prompt =「輸入您的位置:」); n < - as.integer(n); if(is.na(n)){return(as.integer(n))}; ifelse(n == 1,print(「1 is n」),「code for 2」);}' 注意:這個代碼與@Jimbou的評論 –
順便說一下,成爲'if(is.na(n))'這一行。它應該是否定式if(!is.na(n))' –