R Program to Get Input from User

1. Introduction

Taking user input is a fundamental aspect of interactive programming. Whether you're writing scripts for data analysis or building tools, the ability to capture and utilize user input can make your programs more flexible and user-friendly.

2. Program Overview

In this post, we will be creating an R program that captures input from a user and displays it back. We'll be utilizing R's built-in functions to achieve this simple yet crucial task.

3. Code Program

# Prompt the user for input
cat("Please enter your name: ")

# Use the readline function to get the input from the user
user_input <- readline()

# Display the input back to the user
cat("Hello,", user_input, "! Welcome to the R program.\n")

Output:

Please enter your name: John
Hello, John ! Welcome to the R program.

4. Step By Step Explanation

1. We use the cat() function to display a message prompting the user to enter their name. The cat() function in R is used to concatenate and display its arguments.

# Prompt the user for input
cat("Please enter your name: ")

2. The readline() function is used to capture input from the user. This function reads a line from the console (terminal) and can be stored in a variable for future use.

# Use the readline function to get the input from the user
user_input <- readline()

3. Finally, we use the cat() function again to display a message back to the user, incorporating the input we just captured. This gives a personalized greeting based on the user's input.

# Display the input back to the user
cat("Hello,", user_input, "! Welcome to the R program.\n")

Comments