LIVE Instructor-Led Courses
How to Take Input in R Language

31 August 2023

How to Take Input in R Language

R makes it easy to build interactive programs by accepting input from users. Whether it's a simple calculator app or a complex data analysis tool, taking input enables creating customizable R programs.

These guides are part of our training programmes and courses as support material to JBI Trainings R language training

This guide covers the main methods for accepting input in R. You'll learn how to:

  • Use basic functions like scan(), readline(), and read.*() to get input
  • Create interactive programs with menus, dialogs, and keyboard input
  • Follow best practices for validating and handling input safely
  • Apply input techniques to build apps like a BMI calculator

Let's dive in and see how to take input from users in your R code!

Accepting Basic Input in R

R provides several built-in functions to accept input from the user:

The scan() Function

The scan() function reads input from the R console. For example:

vals <- scan() # Enter 5 4 3 2 1 vals #> [1] 5 4 3 2 1

It collects each value entered into a vector.

You can specify types like numeric with what=numeric:

nums <- scan(what=numeric()) # Enter 1 2 three #> Read 2 items nums #> [1] 1 2

This converts the input to numbers, skipping non-numeric values.

To accept multiple lines, set multiLine=TRUE:

para <- scan(multiLine=TRUE) # Enter multiple # lines of input para #> [1] "multiple" "lines" "of" "input"

Overall scan() provides a simple way to get input from the console.

The readline() Function

For reading a single line, use readline(). It prints a prompt, accepts input, and assigns it to a variable:

name <- readline("Enter name: ") name #> [1] "John Doe"

You can customize the prompt or save the result to process later.

Reading Files with read.table() and read.csv()

The read.*() family of functions load input from files:

data <- read.csv("data.csv")

This reads data from a CSV and parses it.

You can specify delimiters, whether to skip lines, data types and more:

read.table("data.txt", sep="|", header=TRUE)

This loads a text file with pipe delimiters and a header row.

These functions make it easy to accept input from saved datasets and process it in R.

Enabling Interactive Input

R also provides functions specifically designed for interactive, real-time input:

Getting Keyboard Input with keyboard()

The keyboard() function waits for the user to press a key:

choice <- keyboard() # Press 'a' choice #> [1] "a"

It returns the character code pressed.

This enables building simple menus:

cat("Press 1 for yes, 2 for no: ") choice <- keyboard() if(choice == "1") { print("You chose yes") } else { print("You chose no") }

File Selection with file.choose()

To pick a file interactively, use file.choose():

file <- file.choose() selected_file <- read.csv(file)

This pops up an open file dialog, reads the CSV into R.

Together keyboard() and file.choose() facilitate interactive input.

Best Practices for Input

When accepting input in R, keep these best practices in mind:

  • Validate the input - check lengths, ranges, formats as needed
  • Sanitize to prevent malicious content
  • Handle errors from bad input gracefully
  • Comment parts dealing with input
  • Limit variables in input scopes

For example:

# Validate input age <- as.numeric(readline("Enter age: ")) if( { print("Invalid age") return() } # Sanitize name <- gsub("<|>|&","",readline("Enter name: ")) # Handle errors num <- tryCatch( { as.numeric(readline("Enter number: ")) }, error = function(e) { print("Invalid number") return() } ) # Comment # Get input from user weight <- readline("Enter weight: ") # Limit variables { height <- readline("Enter height: ") # Process input bmi <- weight / (height^2) print(bmi) }

This produces robust programs by handling invalid, malicious, or unexpected input.

Input Examples and Applications

Let's look at some examples applying input techniques:

BMI Calculator App

Here's an interactive BMI calculator:

# Get input height <- readline("Enter height (m): ") weight <- readline("Enter weight (kg): ") # Calculate BMI bmi <- weight / (height ^ 2) # Output result print(paste("Your BMI is:", bmi))

It uses readline() to get needed values then displays the BMI.

Menu-Driven Program

For a menu:

# Menu options options <- c("Option 1", "Option 2", "Quit") # Show menu cat("Choose an option: \n") print(options) # Get input choice <- keyboard() # Handle selection if(choice == "1") option1() else if(choice == "2") option2() else print("Goodbye!")

This loops until the user picks Quit.

Reading Data Files

To load and process a CSV:

# Select file interactively file <- file.choose() # Read input data <- read.csv(file) # Analyse data summary(data)

Input enables customized data analysis programs.


This guide covered basic functions like scan(), readline(), and read.*() for terminal input, keyboard() and file.choose() for interactive input, and best practices around validation, sanitization and error handling.

Taking input makes R programs flexible, customizable, and reusable. Allowing parameterization and interaction enables building scripts that adapt to users' needs.

Try applying these techniques to create calculators, menus, data munging tools, apps, games, and more! User input unlocks the true power and versatility of R.

This tutorial explained how to accept input from users in R code through functions like scan(), readline(), keyboard() and file.choose(). Taking input enables creating interactive, customizable programs and is key to building reusable R scripts.

If you found this guide useful check out our article on how to run r language in vs code and how to install r language 

Amidst the evolving landscape of modern technology, the course offerings at JBI Training cater to a wide array of interests and expertise. For those who find themselves drawn to the world of data analysis and statistical exploration. Dive deep into the capabilities of the R language, honing your skills to craft dynamic reports and interactive dashboards using the Shiny framework. Unlock the potential to transform complex data into visually engaging and informative presentations.

1. R Language: This foundational course introduces you to the core concepts of the R programming language. Learn about data structures, functions, and control flow to embark on your journey into data analysis and visualization.

2. R - Reporting & Dashboards with Shiny: Elevate your R expertise by delving into Shiny, a powerful web application framework for R. Master the art of creating interactive reports and dashboards that bring your data to life, making complex insights easily accessible.

3. R with RMarkdown and Quarto: Explore the art of reproducible reporting using RMarkdown and Quarto. Learn to create dynamic documents that blend code, analysis, and visualization, ensuring transparency and replicability in your data-driven narratives.

Enrol in these courses and unlock the full potential of the R language for data analysis, reporting, and visualization. Equip yourself with the tools and knowledge to navigate complex datasets, derive meaningful insights, and present your findings effectively.

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

+44 (0)20 8446 7555

[email protected]



Copyright © 2023 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Privacy Policy | Terms & Conditions | Contact Us


Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course