Simple problem, but I can't find an answer that works anywhere. When I use readline() (for example, as demonstrated here - http://www.rexamples.com/4/Reading%20user%20input) it works perfectly:
readinteger <- function()
{
n <- readline(prompt="Enter an integer: ")
return(as.integer(n))
}
a <- print(readinteger())
However, if I add any code after this, readline() is skipped and the code just continues:
readinteger <- function()
{
n <- readline(prompt="Enter an integer: ")
return(as.integer(n))
}
a <- print(readinteger())
b <- 7
Any solutions (and/or easier ways to get user input)?
The problem here is that as soon as a <- print(readinteger())
is entered, it is evaluated, and b <- 7
is interpreted as the input to readline
. A solution is to wrap your code in a function or a block:
{
a <- print(readinteger())
b <- 7
}
By putting everything into a block, the whole block is read as code and only after, as it is evaluated, you will be prompted for an integer.