2016-09-21 55 views
0

我想製作一個程序,用戶將被要求輸入位置,並根據該位置值運行一組特定的代碼。它應該等到用戶輸入位置的值。等到用戶輸入一個值並根據該值運行代碼集

readinteger <- function() 
{ 
    n <- readline(prompt="Enter your location: ") 
    n <- as.integer(n) 
    if (is.na(n)) 
    return(as.integer(n)) 
    } 

LC <- readinteger() 
    if (LC== 1) 
{ 
print(x) 
} 
else if (LC == 2) 
{ 
print(y) 
} 
else 
print(z) 

但在這裏它進行到如果環直接,然後要求輸入位置

+1

是這樣的? 'readinteger < - function(){n < - readline(prompt =「輸入您的位置:」); n < - as.integer(n); if(is.na(n))return(as.integer(n)); ifelse(n == 1,「代碼爲1」,「代碼爲2」)} ' – Jimbou

+0

@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的評論 –

+0

順便說一下,成爲'if(is.na(n))'這一行。它應該是否定式if(!is.na(n))' –

回答

0

如果包含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() 
+0

謝謝..hope這將工作正常... –

0

確定。我認爲這與一次運行整個文件有關。 如果您在Rsudio中運行並且一次只執行一個步驟(即交互式運行),它將起作用。

根據?readline的文檔:`在非交互式使用中,結果就好像響應是RETURN,值是「」。在這種情況下,一種解決方案是再次調用該函數,如下所示:http://www.rexamples.com/4/Reading%20user%20input

我不是100%確定它的工作順利。

對於更復雜的解決你的問題,你可以看到這樣一個問題:Make readline wait for input in R

(注:我加入這個作爲答案只是因爲他格式的緣故,不是一個真正的答案)