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:

A scalar is a single value.Elements are the individual numbers in a vector or matrix.

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:

x <- 1

In most situations, the = sign also functions as an assignment operator. It is easier to type than <-, so feel free to use it.

x = 1

The spaces around the assignment operator are optional, and you can use a more compact style if you wish:

x=1

The <- is called the assignment operator. Instead of typing both characters, I use the Alt+- keyboard shortcut (i.e., press and hold Alt 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.

You Try

Create a variable x by assigning it a value of 5.

Suggested Solution
x <- 5

# If you prefer, the = assignment operator also works:
x = 5

# To display the value of x, just run it on its own line like so:
x
[1] 5

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
You Try

Add 3 + 2 in R

Suggested Solution
3 + 2
[1] 5

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
You Try

Calculate 101 āˆ’ 78 in R.

Suggested Solution
101 - 78
[1] 23

Calculate 29 Ɨ 42 in R.

Suggested Solution
29 * 42
[1] 1218

Calculate 33 squared in R.

Suggested Solution
33 ^ 2
[1] 1089