Note that this and the two next sections (on vectors and [rectangular tables], Sections 1.4 and 1.5) partly repeat material that was mentioned in the introductory parts on Data objects (Sections 1.2.1). However, as they address important topics and cover some new aspects (e.g., in Sections 1.3.4 to 1.3.6), they can be skimmed, but should not be skipped.
In Section 1.2.1, we have learned that scalars are objects of length 1 and how to define objects by assigning names to values. So let’s define some scalar objects and then examine their basic properties:
First, we use assignments to define three (numeric) objects:
Evaluating these assignments creates three new objects
c in our local environment (see the Environment tab of the RStudio IDE or type
ls() in the Console to verify this).
All three objects are of the numeric data type, as they were created by assigning a numeric value to a name.
c was created as the sum of the current values of
c <- a + b).
To do anything with an object, we need to apply functions to them.
We also encountered some generic functions for printing an object, and for checking its shape and type.
Thus, let’s examine the content and characteristics of object
c by these functions:
In contrast to these generic functions, not all R functions can be applied to all objects.
In fact, most functions require specific data shapes or types to work.
As the three objects created here (i.e.,
c) are in
numeric mode (of type
double), we can apply arithmetic functions to them:
Generally, the types of functions that can be applied to an object depends on its properties. Two key object properties that we need to know for this are the shape and the type of an object. Immediately after the assignment, we usually are aware of these properties. However, when working with R, we often deal with a large number of objects and they often change in the process of computing something. Hence, it is good to know that we can always use generic functions to check their shape (e.g., length) and type:
length(c) # 1 could indicate a scalar OR the number of digits... #>  1 length(1000) # Check: also 1 (i.e., NOT number of digits) #>  1 typeof(c) # numbers are of mode "integer" or "double" #>  "double" typeof(3.14159) # decimal numbers are of type "double" #>  "double" typeof(pi) # irrational numbers as well #>  "double" # Note: Objects in "numeric" mode are typically of type "double": typeof(1) # default is "double" #>  "double" typeof(1L) # force to be "integer" #>  "integer"
What about other data types? For instance, we know that R also uses objects of type
Let’s create an object of type
character and examine it by some generic functions:
d <- "word" # note the quotes (""), which could also be ('') d # same as print(d) #>  "word" # type: mode(d) # mode "character" #>  "character" typeof(d) # type "character" #>  "character" # shape: length(d) # a scalar! #>  1 nchar(d) # 4 characters long #>  4 # data structure: is.vector(d) # a vector #>  TRUE is.list(d) # not a list #>  FALSE
Similarly, when defining a scalar object of type
logical, we can apply the same generic functions to it, but receive slightly different results:
e <- b > a # assign (b > a) to an object e e # print(e) #>  TRUE # type: mode(e) # mode "logical" #>  "logical" typeof(e) # type "logical" #>  "logical" # shape: length(e) # a scalar #>  1 nchar(e) # 4 characters long! #>  4 # data structure: is.vector(e) # a vector #>  TRUE is.list(e) # not a list #>  FALSE
Again, depending on the shape and type of an object, different functions are appropriate for probing and processing them.
For instance, the distinction between
nchar() makes sense for objects of type
character, but may yield unexpected results when applied to objects of type
A rather annoying detail of R is the technical distinction between the type and mode of an object. For instance, objects of the types “integer” and “double” are both returned as having the mode “numeric”:
- Further examine the scalars we have just defined (e.g., by combining them, assigning new objects, and checking their
Thus, our exploration shows that objects
c are objects of numeric mode (which can be of type “integer” or of type “double”), whereas
d is a text object (of type “character”), and
e is the result of a test that is either
FALSE (of mode and type “logical”).
nchar() of logical values may yield unexpected results:
length() provides the number of logical values (here: 1, in both cases),
nchar() converts its argument into a “character” object and then counts its number of characters (here: 4 for
TRUE, 5 for
These examples illustrate that “knowing a function” typically implies answering three questions:
- What _task_ does the function address and solve? - Which type and shape of _argument(s)_ does it accept and expect? - What type and shape of _result_ does it return?
- Study the documentations of the
mode()functions to determine their similarities and differences.
The difference between an object’s “mode” and “type” are subtle and not very interesting when first learning R. Both denote some intuitive notion of type — with “mode” capturing this notion more closely, as modes are mutually exclusive and every object has exactly one mode.20
For details on the available modes and types, see 2.1 Basic types of the R Language Definition. The table there shows that only objects of “numeric” mode can have two different types and storage.modes (i.e., “integer” vs. “double”). The table also shows that there exist two more basic types (“complex” and “raw”) that we won’t need in this book.
We learned that R creates objects by assignment and created five different scalar objects (of three different modes/types):
Once an object exists in R, we can always wonder:
- How can we change a scalar object in R?
Actually, Section 1.2.3 already answered this question in a general fashion:
- To change an object, we simply re-create (i.e., re-assign) it with a different definition.
As this answer said nothing about the object’s shape or type, we can simply apply it to scalar objects. Thus, to change an existing scalar object, we need to re-assign it — which is the same as re-creating it:
# Check values (defined above): a #>  1 b #>  2 a/b #>  0.5 a <- 100 # changes a a # a has changed #>  100 a/b # a/b changes when a has been changed #>  50 b <- 500 # changes b b # b has changed #>  500 a/b # a/b changes when b has been changed #>  0.2 d # (assigned above) #>  "word" d <- "weird" # changes d d # d has changed #>  "weird"
A related question (also answered in Section 1.2.3) is:
- What happens to an existing scalar object when we re-assign data of a different type to it?
In principle, assigning data of a different type to an object could either cause an error or change the object’s data type.
To see what happens, let’s simply assign a variety of data types to object
This example shows that re-assigning an object really works just like creating a new object. Whatever was assigned to the object prior to an assignment is forgotten and lost at the moment of a new assignment.21
The fact that objects change when new contents are assigned to them also implies that the order of evaluations matters:
The same object (e.g., a scalar
d or an expression
a/b) can have different contents at different locations and at different times. (Note that the line numbers to the left of your editor window mark locations and that R scripts are typically evaluated in a top-down fashion.)
We have applied some simple functions to data arguments above, but not all functions can be applied to all data. Importantly, most functions require specific types of arguments to work (i.e., the types of the arguments must match the required argument types of the function). When viewing this requirement from the perspective of existing objects, the type of an object determines which functions can be applied to it:
# Numeric objects: a #>  100 typeof(a) # a generic function (working with all object types) #>  "double" length(a) # a scalar #>  1 a + b #>  600 sum(a, b) # an arithmetic function (requiring numeric object types) #>  600 # Character objects: d #>  "wow" typeof(d) #>  "character" length(d) # a scalar #>  1 nchar(d) # the "length" of a character object #>  3 # Logical objects: e #>  TRUE typeof(e) #>  "logical" !e # negation (reverses logical value) #>  FALSE !!e #>  TRUE isTRUE(e) # tests a logcial expression #>  TRUE isTRUE(!e) #>  FALSE e == !!e # tests equality #>  TRUE
In case of a mismatch between function and object types, an error may occur. For instance, arithmetic functions typically require numeric data and yield errors when applied to text (i.e., character data).
Some of the most common functions apply primarily to numeric objects and create new numeric objects. Examples of so-called arithmetic functions (or operators) include the following:
# Arithmetic functions: + 2 # keeping sign #>  2 - 3 # reversing sign #>  -3 1 + 2 # addition #>  3 3 - 1 # subtraction #>  2 2 * 3 # multiplication #>  6 5 / 2 # division #>  2.5 2^3 # exponentiation #>  8 5 %/% 2 # integer division #>  2 5 %% 2 # remainder of integer division (x mod y) #>  1
When an arithmetic expression contains more than one operator, the issue of operator precedence arises. Fortunately, R uses the same precedence rules as we have learned in school — the so-called “BEDMAS” order:
?Syntax provides a longer list of operator precedence. However, using parentheses to structure longer (arithmetic or logical) expressions increases transparency and is recommended.
All arithmetic operators can not only be used with numbers (or data objects for which
is.numeric is TRUE), but also with scalar objects that are assigned to numbers:
x <- 5 y <- 2 + x # keeping sign #>  5 - y # reversing sign #>  -2 x + y # addition #>  7 x - y # subtraction #>  3 x * y # multiplication #>  10 x / y # division #>  2.5 x ^ y # exponentiation #>  25 x %/% y # integer division #>  2 x %% y # remainder of integer division (x mod y) #>  1
Actually, arithmetic operators also work with (numeric) vectors (see Exercise 5 in Section 1.8.5) and some arithmetic functions also work with non-numeric (e.g., logical) objects.
By applying logical operators to numeric objects, we get logical values (i.e., scalars of type
logical that are either
FALSE). For instance, each of the following comparisons of numeric values yields a logical object (i.e., either
FALSE) as its result:
== tests for the equality of objects, whereas
!= tests for their inequality (or non-equality):
A common typo of R novices and inattentive R developers is to use
= instead of
= can be used as an alternative for the assignment operator
<-, this often yields unexpected results or “assignment” errors.
== operator often yields unexpected results when checking the equality of two numbers.
As computers store (real) numbers as approximations,
x == y often evaluates to
FALSE even we mathematically know that
y should be equal. For example:
When checking for the equality of numbers, we need to use functions that allow for minimal tolerances due to the way in which computer represent so-called floating point numbers. One such function is the
Beyond numeric comparisons, the logical operators
| (or), and
! (not) allow for logical expressions and yield logical objects (i.e.,
FALSE) as their result:
- Assignment vs. testing for numeric equality:
- Predict, evaluate, and explain the results of the following three expressions:
- How can we change the third expression to obtain the (mathematically correct) result
- Logical expressions:
?base::Logicto see and read the help page on logical operators.22
- Look up De Morgan’s Laws (e.g., on Wikipedia) and express them in R.
Hint: Verify their truth by evaluating them for two objects A and B that are assigned to arbitrary truth values.
The potential for confusion is aggravated by the fact that objects also belong to some “class”, but an object can have multiple classes assigned to it, which can easily be changed by the user.↩︎
When programming in R, this statement will be qualified by the notion of variable scope. Variables with identical names can co-exist at multiple levels. Re-assigning an object overwrites any previous object at the current level.↩︎
The Examples of
?base::Logicillustrate a somewhat problematic regularity of R: They are informative for experienced users, but are often difficult to understand for beginners. Nevertheless, copying and trying to understand examples is a good way to learn more about a particular topic.↩︎