4.1 Prompting the User
One way to control the flow of a program is to arrange for it to pause and await information from the user who runs it.
Up to this point any information that we have wanted to process has had to be entered into the code itself. For example, if we want to print out a name to the console, we have to provide that name in the code, like this:
person <- "Dorothy" cat("Hello, ", person, "!\n", sep = "")
## Hello, Dorothy!
We can get any printout we like as long as we assign the desired string to
person—but we have to do that in the code itself. But what if we don’t know the name of the person whom we want to greet? How can we be assured of printing out the correct name?
readline() function will be helpful, here. It reads input directly from the console and produces a character vector (of length one) that we may use as we like. Thus
person <- readline(prompt = "What is your name? ") # Type your name before running the next line! cat("Hello, ", person, "!\n", sep = "")
## What is your name? Cowardly Lion ## Hello, Cowardly Lion!
Note that the input obtained from
readline() is always a character vector of length one—a single string—so if you plan to use it as a number then you need to convert it to a number. The
as.numeric() function will do this for you:
number <- readline("Give me a number, and I'll add 10 to it: ") # Give R your number before you run the next line! cat("The sum is: ", as.numeric(number) + 10)
## Give me a number, and I'll add 10 to it: 15 ## The sum is: 25
4.1.1 Practice Exercises
Try out the following code:
pet <- readline("Enter the name of your pet: ") type <- readline("What kind of animal is it? (Dog, cat, etc.): ") cat(pet, " is a ", type, ".\n", sep = "")
Important: Run the lines one at a time, not all three at once. R will stop after the first line, waiting for your answer. If you try to run line 2 along with the
petline, then line 2 will become your attempted input for
pet, resulting in an error.
4.1.2 Solutions to the Practice Exercises
Here’s one possible outcome in the Console:
> pet <- readline("Enter the name of your pet: ") Enter the name of your pet: Bo > type <- readline("What kind of animal is it? (Dog, cat, etc.): ") What kind of animal is it? (Dog, cat, etc.): dog > cat(pet, " is a ", type, ".\n", sep = "") Bo is a dog.