Make readline wait for input in R

后端 未结 2 839
不思量自难忘°
不思量自难忘° 2020-11-30 09:19

I\'m trying to make my code ask me for a \"TRUE\" or \"FALSE\" value before proceeding.

It currently works fine if I run it one line at a time, however when I run a

2条回答
  •  清歌不尽
    2020-11-30 09:32

    If you want to do this in interactive mode then you already have answers but not for use with Rscript. For that instance you need to send messages to the console with cat:

    If this test file is named 'prompt.r' and is in the directory where you are working in a system console session:

    cat("a string please: ");
    a <- readLines("stdin",n=1);
    cat("You entered")
     str(a);
    cat( "\n" )
    

    Then you can run it from the command line as

    $ Rscript prompt.r
    

    If you want an all-purpose script then this would run your script under interactive conditions and my script for non-interactive ones:

    if (interactive() ){raw <- 
                 readline("TRUE or FALSE -- this is a validation run: ")
    
                    if (raw == "F" | raw == "FALSE" | raw == "False"){
                   validation <- F
                     } else{
                         validation <- T
                           }
               rm(raw)  } else{
    #  non-interactive
    cat("a string please: ");
    a <- readLines("stdin",n=1);
    cat("You entered")
     str(a);
    cat( "\n" )}
    

提交回复
热议问题