简体   繁体   中英

Readline() in R reads the next line

I want some user input and I want to use readline for that. However, when I execute the code below it uses "test <- "sometext" directly as input and does not wait for the user to respond.

How can I let the code stop running whenever I call readline, so that R waits for the user to respond?

fun <- function() {
   ANSWER <- readline("Are you a satisfied R user? ")
   if (substr(ANSWER, 1, 1) == "n")
     cat("This is impossible.  YOU LIED!\n")
   else
     cat("I knew it.\n")
}
fun()
test <- "sometext"
someCode <- "someCode"

This gives the following output:

> fun <- function() {
+   ANSWER <- readline("Are you a satisfied R user? ")
+   if (substr(ANSWER, 1, 1) == "n")
+     cat("This is impossible.  YOU LIED!\n")
+   else
+     cat("I knew it.\n")
+ }
> fun()
Are you a satisfied R user? test <- "sometext"
I knew it.
> someCode <- "someCode"

R is waiting for input and perceives the code after the fun() call (that is copied pasted eg test <- "sometext" ) is the input. If you don't want this to happen, you can wrap the calls into their own function and call that function:

foo = function(){
    fun()
    test <- "sometext"
    someCode <- "someCode"
}
foo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM