3 Scalars
Scalars are single numeric values. They are the elements that compose vectors and matrices. Usually a scalar is represented as an italicized lowercase letter:
x = 9
Technically, there are no scalars in R. Pretty much everything in R is a vector of one kind of another, meaning that most variables can have multiple elements instead of being restricted to a single element. However, a vector with just one element is often treated like a scalar. This everything-is-a-vector feature of R makes a lot of things nice and easy for data analysis, though certain kinds of computations can be slower because of it.
3.1 Variable Assignment
If you want to make a āscalarā in R, you assign a value to a variable name like so:
<- 1 x
In most situations, the =
sign also functions as an assignment operator. It is easier to type than <-
, so feel free to use it.
= 1 x
The spaces around the assignment operator are optional, and you can use a more compact style if you wish:
=1 x
The <-
is called the assignment operator. Instead of typing both characters, I use the Alt+-Alt+- keyboard shortcut (i.e., press and hold AltAlt while pressing -
), which puts spaces around the assignment operator. Unfortunately, keyboard shortcuts work in RStudio only. They do not yet work inside the in-browser exercises of this book.
3.2 ScalarāScalar Operations
Scalar operations are the basic arithmetical operators you are familiar with: addition, subtraction, multiplication, division, and exponentiation.
For example,
4 + 1 = 5
4 and 1 are both scalars, and adding them results in a scalar (i.e., 5).
In R, scalar operations like addition are straightforward:
4 + 1
[1] 5
By convention, we put spaces around most operator symbols (e.g., +
, -
, *
, /
, ^
, =
) because it makes complex code easier to read. However, the spaces are optional, and R does not care if things look messy:
# Scalar addition
# Putting single spaces around the + operator looks nice
4 + 5
[1] 9
# R does not need spaces, though
4+5
[1] 9
# R does not care if you are inconsistent or have multiple spaces
4 + 5
[1] 9
Other basic operators are also straightforward. Scalar subtraction with the -
operator:
4 - 1
[1] 3
Scalar multiplication with the *
operator:
5 * 6
[1] 30
Scalar division with the /
operator:
6 / 3
[1] 2
Scalar exponentiation with the ^
operator:
3 ^ 2
[1] 9
4 ^ -1
[1] 0.25
4 ^ .5
[1] 2