Learn/R/3. Reading input and arithmetic
Lesson 3 of 8
Sign in

R, lesson 3

Reading input and arithmetic

Most programs need data from outside. In this course, input arrives on standard input (stdin), the stream a program reads when you type into it or pipe a file into it. R reads it with readLines():

lines is now a character vector with one element per input line. Use square brackets to pick a line by its position. R counts from 1, not 0:

Why file("stdin") and not just stdin()? When R runs a script, stdin() can refer to the script itself rather than the data you send it. file("stdin") always means the real input stream. If the last line of input has no newline, R prints a warning; it still reads the line, and the warning goes to stderr, which the exercises ignore.

Text into numbers

Everything read from input is text. "7" + 1 is an error, because R will not add text. Convert first:

2 exercises to try what you just read.

Exercise 1

Add two numbers

Press Ctrl Enter or Check to test your code.

Exercise 2

Movie marathon

Press Ctrl Enter or Check to test your code.

If a line holds several numbers separated by spaces, split it and convert the pieces in one go:

You will learn exactly what strsplit() and [[1]] do in later lessons; for now it is a handy recipe. Once you have several numbers, sum(nums) adds them all up and length(nums) tells you how many there are.

Arithmetic operators

OperatorMeaningExampleResult
+, -, *add, subtract, multiply7 * 321
/divide (always gives decimals)7 / 23.5
^power2 ^ 101024
%/%whole-number division17 %/% 53
%%remainder17 %% 52

Usual maths precedence applies: ^ first, then * and /, then + and -. Use parentheses when in doubt. %/% and %% pair up nicely: 130 minutes is 130 %/% 60 hours and 130 %% 60 minutes.

Useful maths functions include round(x, digits), sqrt(x), abs(x), floor(x) and ceiling(x).

Printing results neatly

cat() shows up to 7 significant digits, so cat(10 / 3) prints 3.333333. When you need a fixed number of decimals, format the number with sprintf():

sprintf() returns text built from a pattern: %.2f means "a number with 2 decimals", %d means "a whole number" (a value such as 7.5 makes it fail, so round first), and %s means "a string".

Further reading

  • An Introduction to R, section "Vector arithmetic"
  • R documentation: readLines()
  • R documentation: Arithmetic operators

Read two whole numbers, one per line, and print their sum.

Sample input:

Sample output:

You plan to watch some films back to back. The input is one line with the running times of the films in minutes, separated by spaces. Print the total time as hours and minutes in the form H h M min.

Sample input:

Sample output:

(95 + 120 + 88 = 303 minutes, which is 5 hours and 3 minutes.)

lines <- readLines(file("stdin"))
name <- lines[1]
cat("Hello,", name, "\n")
lines <- readLines(file("stdin"))
a <- as.numeric(lines[1])   # decimal numbers
n <- as.integer(lines[2])   # whole numbers
nums <- as.numeric(strsplit(lines[1], " ")[[1]])   # "3 4 5" becomes 3 4 5
cat(sprintf("%.2f", 10 / 3), "\n")   # 3.33
2
3
5
95 120 88
5 h 3 min