readline inserts a line break before the prompt in the R console - r

How can I get a user keyboard input on the current line of the R console?
I have prior output from cat and now want a readline(prompt="") in the same line.
I.e. there should be no line break before the prompt.
I have tried cat("Dummy") ; readline("\r Type sth: ") to no avail.
I cannot include "Dummy" in the prompt call as this is supposed to be a two step process (Some info in the console, prompt user input, more info in the same line, prompt second user input).
Edit: I came up with something that technically works but is not elegant:
{
cat("\014") # clear the entire console
p1 <- readline("prompt1: ")
cat("\014") # clear again, then repeat previous text
p2 <- readline(paste0("promt1: ", p1, ". prompt2: "))
}
A variant without clearing the console is still wanted.

Related

Ask for user multiple-line input during R-script execution [duplicate]

I am trying to use
var <- as.numeric(readline(prompt="Enter a number: "))
and later use this in a calculation.
It works fine when running in RStudio but I need to be able to pass this input from the command line in Windows 10
I am using a batch file with a single line
Rscript.exe "C:\My Files\R_scripts\my_script.R"
When it gets to the user input part it freezes and it doesn't provide expected output.
From the documentation of readline():
This can only be used in an interactive session. [...] In non-interactive use the result is as if the response was RETURN and the value is "".
For non-interactive use - when calling R from the command line - I think you've got two options:
Use readLines(con = "stdin", n = 1) to read user input from the terminal.
Use commandArgs(trailingOnly = TRUE) to supply the input as an argument from the command line when calling the script instead.
Under is more information.
1. Using readLines()
readLines() looks very similar to readline() which you're using, but is meant to read files line by line. If we instead of a file points it to the standard input (con = "stdin") it will read user input from the terminal. We set n = 1 so that it stops reading from the command line when you press Enter (that is, it only read one line).
Example
Use readLines() in a R-script:
# some-r-file.R
# This is our prompt, since readLines doesn't provide one
cat("Please write something: ")
args <- readLines(con = "stdin", n = 1)
writeLines(args[[1]], "output.txt")
Call the script:
Rscript.exe "some-r-file.R"
It will now ask you for your input. Here is a screen capture from PowerShell, where I supplied "Any text!".
Then the output.txt will contain:
Any text!
2. UsingcommandArgs()
When calling an Rscript.exe from the terminal, you can add extra arguments. With commandArgs() you can capture these arguments and use them in your code.
Example:
Use commandArgs() in a R-script:
# some-r-file.R
args <- commandArgs(trailingOnly = TRUE)
writeLines(args[[1]], "output.txt")
Call the script:
Rscript.exe "some-r-file.R" "Any text!"
Then the output.txt will contain:
Any text!

How to get a user input in command prompt and pass it to R

I am trying to use
var <- as.numeric(readline(prompt="Enter a number: "))
and later use this in a calculation.
It works fine when running in RStudio but I need to be able to pass this input from the command line in Windows 10
I am using a batch file with a single line
Rscript.exe "C:\My Files\R_scripts\my_script.R"
When it gets to the user input part it freezes and it doesn't provide expected output.
From the documentation of readline():
This can only be used in an interactive session. [...] In non-interactive use the result is as if the response was RETURN and the value is "".
For non-interactive use - when calling R from the command line - I think you've got two options:
Use readLines(con = "stdin", n = 1) to read user input from the terminal.
Use commandArgs(trailingOnly = TRUE) to supply the input as an argument from the command line when calling the script instead.
Under is more information.
1. Using readLines()
readLines() looks very similar to readline() which you're using, but is meant to read files line by line. If we instead of a file points it to the standard input (con = "stdin") it will read user input from the terminal. We set n = 1 so that it stops reading from the command line when you press Enter (that is, it only read one line).
Example
Use readLines() in a R-script:
# some-r-file.R
# This is our prompt, since readLines doesn't provide one
cat("Please write something: ")
args <- readLines(con = "stdin", n = 1)
writeLines(args[[1]], "output.txt")
Call the script:
Rscript.exe "some-r-file.R"
It will now ask you for your input. Here is a screen capture from PowerShell, where I supplied "Any text!".
Then the output.txt will contain:
Any text!
2. UsingcommandArgs()
When calling an Rscript.exe from the terminal, you can add extra arguments. With commandArgs() you can capture these arguments and use them in your code.
Example:
Use commandArgs() in a R-script:
# some-r-file.R
args <- commandArgs(trailingOnly = TRUE)
writeLines(args[[1]], "output.txt")
Call the script:
Rscript.exe "some-r-file.R" "Any text!"
Then the output.txt will contain:
Any text!

How can code execution be paused until a key is pressed?

I'm trying to get R to pause code execution, for the user to review some prior console output, to verify that file links have been correctly matched (using RegEx to match file names to their respective objects).
From some other answers, I've come up with:
readline(prompt="Press [enter] to continue or [esc] to exit")
As a stand alone line of code, this works as expected, but as soon as I add code below it, and send the whole block to the console, it runs right through the readline call without stopping:
readline(prompt="Press [enter] to continue or [esc] to exit")
x <- 1
y <- 2
Is there a way to get R to actually pause here?
I've also tried wrapping readline in a function, but it still doesn't work
pause <- function(){
p <- readline(prompt="Press [enter] to continue or [esc] to exit")
return(p)
}
pause()
x <- 1
y <- 2
Edit:
If I call the script via source(), readline does work properly. Is there a way to get that behavior without doing that?
By "send the whole block to the console", it sounds like you are copy-pasting your code into a running R instance.
If you do that, R will run each line in the order it receives it, as soon as it receives it. If any of the lines tries to take input, that input will come from whatever you are copy-pasting. So if you copy-paste this:
readline(prompt="Press [enter] to continue or [esc] to exit")
x <- 1
y <- 2
R will read and run the first line first. That first line will run and read the next line of input (which is a blank line here). Then R will come back and read and execute the other two lines.
You need to get your code entered into R completely before any of it runs. Try wrapping the whole thing in a function:
dostuff <- function(){
readline(prompt="Press [enter] to continue or [esc] to exit")
x <- 1
y <- 2
}
dostuff()
Using scan would always work:
message("Press [enter] to continue or [esc] to exit")
scan(quiet = TRUE, what = "")

Rscript and user prompts

Have a fully working R-script. When executing it from Rscript it doesn't stop to accept user input however.
The user input is some readline statements. The cat statements prompting for input works as intended. Have I missed something?
I execute 'Rscript scriptfile.R' from terminal on macOS.
You can create a function typeline() to read an input line and then use the result for your next commands. It will wait for your input text either you run your code in Rstudio or in terminal:
typeline <- function(msg="Enter text: ") {
if (interactive() ) {
txt <- readline(msg)
} else {
cat(msg);
txt <- readLines("stdin",n=1);
}
return(txt)
}
txt=typeline("your message: ")
print(txt)
Managed to get it to work by changing readline to readLines as mentioned in the post suggested by meenaparam. The downside with this method is that ithe script only works in batch mode, running it in Rstudio makes it hang. Would be good to know a general way to capture keyboard input i.e that works both in interactive and batch mode.
Use this
cat("What's your name? ")
name <- readLines(file("stdin"),1)
cat("What's your age? ")
age <- readLines(file("stdin"),1)
print(name)
print(age)

R: I fail to pause my code

I am trying to pause my code for a little while, time for me to observe the plots.
I tried:
print('A')
something = readline("Press Enter")
print('B')
print('C')
, then there is no pause, the line print('B') is fed to readline and get stored into something and therefore only A and C got printed on the screen. Note that if I add an empty line between Something = readline("Press Enter") and print("B"), then print("B") get printed on the screen but still the console doesn't allow the user to press enter before continuing.
And I tried:
print('A')
Sys.sleep(3)
print('B')
print('C')
The program waits 3 seconds before starting and then run "normally" without doing any pause between print('A') and print('B').
What do I missunderstand?
Here is my R version: R 3.1.1 GUI 1.65 Snow Leopard build (6784)
The problem with readline is that if you paste your script into an R console, or execute it from eg Rstudio, the redline function is read and then the next line of the script is read in as the console entry, which in your case sets the value of something to print('B).
An easy way to get around this is to stick your entire code in a function, then call the function to run it. So, in your case:
myscript = function(){
print('A')
something = readline(prompt = "Press Enter")
print('B')
print('C')
}
myscript()
The output of this for me (in Rstudio, with R version 3.1.1):
[1] "A"
Press Enter
[1] "B"
[1] "C"
This has always felt like a bit of a hack to me, but it's essentially what the readline documentation recommends in its example.
I've never used sleep in my code, so I can't help you there.
Edit to clarify based on comments: This will only work if myscript() is the very last line of your script, or if it is manually entered into the console after running the script to generate the function. Otherwise, you will run into the same problem as before- the next line of code will be automatically entered.

Resources