R, lesson 1
R is a language built for working with data: numbers, tables, statistics and charts. Before any
of that, you need a way to see results. R gives you two everyday tools for output, cat() and
print(), and they behave differently.
cat() writes its arguments exactly as they are, with a space between them. It does not
start a new line at the end, so you add "\n" (the newline character) yourself:
The sep argument changes what goes between the pieces. sep = "" glues them together:
Because cat() prints exactly what you ask for, it is the right choice when a program must
produce output in a precise format, which is what every exercise in this course checks.
print() shows a value the way R sees it, with a position marker such as and quotes
around text:
2 exercises to try what you just read.
[1]That [1] means "this line starts with element number 1". R thinks of almost everything as a
vector (a sequence of values), and even a single number is a vector of length one. You will
see why that matters in later lessons. print() is great for checking what a variable holds,
but its decorations make it a poor fit for exact output.
Everything after a # on a line is a comment. R skips it. Use comments to explain why the code
does something:
R reads your file from top to bottom and runs each line in order. If a line fails, R stops and
writes an error message starting with Error. Some problems only produce a Warning: R keeps
going, but you should still read it, because it usually means a value is not what you expected.
Text goes in double or single quotes; R treats "hi" and 'hi' the same. Inside quotes, \n
means newline and \t means tab.
Write a program that prints exactly these two lines:
The program reads no input.
Print a date stamp and a price tag using cat():
2026-11-09. Print it with one cat() call that receives the three
values "2026", "11" and "09" as separate arguments.Apples: 3 for $2. Print it with one cat() call that receives
"Apples:", the number 3, "for" and "$2".Expected output:
cat("Hello, World!\n")
cat("Total:", 42, "\n") # Total: 42 (note the space before the newline)cat("2026", "11", "09", sep = "-") # 2026-11-09 with no newline after it
cat("\n")
cat("Score: ", 87, "%\n", sep = "") # Score: 87%print("Hello") # [1] "Hello"
print(3.5) # [1] 3.5# Greet the user
cat("Hi!\n") # a comment may follow codeHello, World!
I am learning R.2026-11-09
Apples: 3 for $2