R, lesson 3
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.
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.
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.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+, -, * | add, subtract, multiply | 7 * 3 | 21 |
/ | divide (always gives decimals) | 7 / 2 | 3.5 |
^ | power | 2 ^ 10 | 1024 |
%/% | whole-number division | 17 %/% 5 | 3 |
%% | remainder | 17 %% 5 | 2 |
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).
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".
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 numbersnums <- as.numeric(strsplit(lines[1], " ")[[1]]) # "3 4 5" becomes 3 4 5cat(sprintf("%.2f", 10 / 3), "\n") # 3.332
3595 120 885 h 3 min