3

I am developing an R script in RStudio that requires the user to input two values (a first name and a last name). These inputs will later be used for pattern matching of a text document.

In Python, raw_input would be used to gather these values and I understand that readline(prompt = ) is the associated function in R, but I cannot seem to have my script stop to ask for a value. Instead it appends the next line of code.

My function to prompt the user for names is:

askForName <- function(firstOrLast){
  if(firstOrLast == "first"){
    x <- readline(prompt = "Enter first name: ")
  }
  else if(firstOrLast == "last"){
    x <- readline(prompt = "Enter last name: ")
  }
  return(x)
}

When I run:

firstName <- askForName("first")
lastName <- askForName("last")

The console returns:

> firstName <- askForName("first")
Enter first name: lastName <- askForName("last")

How can I get R to wait for a user-inputted value before proceeding through the script?

user3271783
  • 113
  • 6
  • This is not how you do this. Anyway, the documentation clearly says "[readline] can only be used in an interactive session.". – Roland Apr 12 '16 at 15:12
  • Either let your user input the parameters as function parameters or go all the way and use something like shiny. – Roland Apr 12 '16 at 15:13

3 Answers3

1

If you run a script containing those function calls, it will work correctly. The problem in this case is that you are pasting a line after the "readline" call. I have just tested this and it works fine, as it does in production code used by the company I work for.

test.R:

askForName <- function(firstOrLast){
  if(firstOrLast == "first"){
    x <- readline(prompt = "Enter first name: ")
  }
  else if(firstOrLast == "last"){
    x <- readline(prompt = "Enter last name: ")
  }
  return(x)
}

firstName <- askForName("first")
lastName <- askForName("last")

Then:

source("test.R")
Enter first name: Alan
Enter last name: O'Callaghan
alan ocallaghan
  • 3,116
  • 17
  • 37
1

Try this instead of readline:

cat("a string please: ")
a <- readLines("stdin",n=1);
cat(a, "\n")
IRTFM
  • 258,963
  • 21
  • 364
  • 487
0

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

firstname=typeline("firstName: ")
secondname=typeline("secondName: ")

print(firstname)
print(secondname)
rafaoc
  • 586
  • 7
  • 21