R, lesson 2
A variable is a name that points to a value. In R you create or change one with the
assignment arrow <-, read as "gets":
You can also write = for assignment, and you will see it in other people's code. The arrow is
the traditional R style and avoids confusion with = inside function calls, so this course uses
<-. Assigning again simply replaces the old value:
Every value has a type. You can ask for it with class():
| Example | class() | What it is |
|---|---|---|
3.5, 42 |
2 exercises to try what you just read.
"numeric" |
| a number with decimals (a "double") |
42L | "integer" | a whole number; the L asks for an integer |
"tea" | "character" | text, called a string |
TRUE, FALSE | "logical" | yes/no values |
Note that a plain 42 is numeric, not integer. R stores most numbers as doubles, and for
everyday maths you rarely need to care. Write TRUE and FALSE in full; the short forms T and
F are ordinary variables that someone could overwrite.
There is also NA, which means "a value is missing". It is not zero or empty text, and any
calculation that touches it usually gives NA back.
Functions named as.<type>() convert values:
If the text is not a number, as.numeric("abc") returns NA with a warning instead of
stopping your program, so check your data.
Names can contain letters, digits, dots and underscores, and must start with a letter (or a dot
not followed by a digit). They are case-sensitive: total and Total are different variables.
Pick names that describe the value, and use one style consistently; this course uses
snake_case, such as price_per_kg.
R has no const keyword. The convention for a value that should never change is to give it a
clear name near the top of the script, and simply not reassign it:
Comparisons produce logical values, which you can store like anything else:
The starter defines three variables for an order. Create a variable total that holds
price * quantity, and a variable in_stock that is TRUE when quantity is greater than 0.
Then print exactly:
Use the variables in your cat() calls rather than typing the values.
Print the class of each of these four values, one per line, using class():
42, 42L, "42" and TRUE. Expected output:
city <- "Lisbon"
temperature <- 21.5
cat(city, "is", temperature, "degrees\n") # Lisbon is 21.5 degreestemperature <- 23as.numeric("3.75") # 3.75
as.integer(9.8) # 9 (drops the decimals)
as.character(12) # "12"VAT_RATE <- 0.2stock <- 7L
in_stock <- stock > 0
cat("In stock:", in_stock, "\n") # In stock: TRUEItem: Notebook
Total: 10
In stock: TRUEnumeric
integer
character
logical