R program to take input from user and display it

Asking for user input and printing them out in R programming language

In this article, we will learn How to take input from the user keyboard and display it in the terminal in the R programming language.

Open any text editor and write down the below code then save it as app.r in your R programming practice directory.

R program to take user input and display it

name = readline(prompt="Enter your name: ")
addr = readline(prompt="Enter your address: ")
phone = readline(prompt="Enter your phone: ")

print(paste("You are", name))
print(paste("You are located at", addr))
print(paste("We maybe reach you on", phone))

Now run the program by typing Rscript app.r in the terminal. You should get the following output.


Sample Input Sample Output
Enter your name: Mehrab Mohul <Enter>
Enter your address: Tampa <Enter>
Enter your phone: +4434547698
[1] “You are Mehrab Mohul”
[1] “You are located at Tampa”
[1] “We maybe reach you on +4434547698”

Note: <Enter> indicates ‘Pressing the Enter key

Code Analysis

In the first line of code, we have declared the name variable for storing the input from the keyboard. Here we used the readline and prompt method to ask for input. It is a built-in method for taking input in R.

In the same way, we asked for the address and phone number. Here notice that we used the same method for taking string and integer. And also we didn’t declare the data types for string and integer. It is because R is a very high-level programming language, it don’t need type declarations. So that R is a very loosely typed language.

And finally, we have printed the user information with our given template using the print statement.And the syntax/grammer we have used to structure the programis the built-in echosystem. So use the syntax for taking any input and printing.

Happy coding 🙂

Posted in