[1] 5 6 7 8 9 10 11 12 13 14 15
(Sections 2.2-2.5)
Consider the seq()
function:
The default value of the parameter by
is 1, so we could get the same thing with:
to
, But Not Past ItA shortcut for sequencing, when by
is 1 or -1.
Going up …
Going down …
We can apply rep()
to a vector of length greater than 1:
rep
Character Vectorseach
Parameter for rep()
times
In order to make:
Write:
Write one-line commands to produce each of the following:
Sub-setting
The operation of selecting one or more elements from a vector.
Recall heights
:
Find subsets of vectors using brackets:
If we want two or more elements, then we specify their indices in a vector.
Also OK to be direct:
We can replace more than one element:
The subset of indices may be as complex as you like:
Boolean expressions are expressions that evaluate to a logical vector:
Operation | What It Means |
---|---|
< | less than |
> | greater than |
<= | less than or equal to |
>= | greater than or equal to |
== | equal to |
& | and |
| | or |
! | not |
Why?
The equality (==
) operator indicates whether the expressions being compared evaluate to the same value.
Made with two equal-signs, not one!
It’s not about strict identity.
After all:
c(2, 3, 6, 7)
has length 4Answer: the 5 was recycled.
Recycling
An automatic process by which R, when given two vectors, repeats elements of the shorter vector until it is as long as the longer vector.
Recycling enables the two resulting vectors to be combined element-wise in operations.
Recall our heights
vector:
Scarecrow Lion Tinman Dorothy Toto Boq
72 70 69 58 NA 45
We want the heights of Scarecrow, Tinman and Dorothy. Here’s one way:
Select those persons whose heights exceed a certain amount.
We think: “Select from people
, where people
is at least 70.”
Get the ages of people who are over 70 inches tall.
Get the heights of people who are less than 60 years old and who also like Toto.
How many people are no more than 70 inches tall?
Write one-line commands to find:
NA
on Sub-SettingScarecrow Lion Tinman Dorothy Toto Boq
72 70 69 58 NA 45
Scarecrow Lion Tinman Dorothy Toto Boq
TRUE TRUE TRUE FALSE NA FALSE
Toto’s height was missing.
NA
to the Toto-element of the tall
vector.which()
Applied to a logical vector, the which()
function returns the indices of the vector that have the value TRUE
:
Find the indices of heights
where the heights are at least 65:
any()
Is anyone more than 71 inches tall?
Yes: the Scarecrow is more than 71 inches tall.
%in%
-OperatorA shortcut to the previous constrcutions involving any()
:
all()
Is everyone more than 71 inches tall?
Careful about NA
s! Is everyone more than 40 inches tall?
Toto’s height is NA
so R can’t say whether all the heights are bigger than 40.