1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! I had played with brackets, thinking it was the answer - but apparently didn't get it right. One important thing I just figured out though - NOTHING can be after the last bracket. Not even blank lines or empty space. That's very important.
I seem to have run into a followup problem. Using this method, I can only get the lest line of code returned from the bracketed section. Example: readinteger <- function() { n <- readline(prompt="Enter an integer: ") return(as.integer(n)) } { a <- print(readinteger()) b <- a + 10 c <- 20 a b c } In that code, the only results displayed are a (the user input) and c (the last line of code)
You'll need to use print.
:facepalm: I didn't even think that one through. Thanks again!
0

put multiple outputs if processed by your function or the print function into "ONE object"

you name it: myOput <- list(abandoned.b,that.c) print(myoutput)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.