What will happen when you enter these commands? Try it out.
[1] 10
[1] 21
[1] 0.4761905
If you’re working with very large numbers you can use scientific notation:
[1] 2e+10
[1] 2e+10
[1] TRUE
In that last line we used the comparison operator ==
; it tests whether or not two values are equivalent.
You can see how many elements a vector holds using the length
function:
[1] 1
[1] 1
[1] 10
[1] 1 2 3 4
[1] 15 16 17 18
[1] 10 12 14 16
[1] 6 8 8 10
Warning in d + c(1, 2, 3): longer object length is not a multiple of
shorter object length
[1] 6 8 10 9
So, for example, we could flip the sign of every other number in a vector with:
[1] 5 -6 7 -8
[1] "a"
[1] TRUE
[1] "a" "b" "c" "d"
a b c
a
b
c
Boolean can either be “True” or “False”, and represent a variable with binary values. To create Boolean use TRUE
or FALSE
:
[1] TRUE
[1] FALSE
[1] TRUE TRUE FALSE
[1] FALSE
[1] 1 2 NA 4
[1] "a" NA "c" NA
[1] TRUE FALSE NA FALSE
[1] FALSE TRUE
NULL
is used to signify unassigned variables:
NULL
[1] TRUE
Let’s say we have a vector of numbers:
We can extract elements from 1D vectors using the index syntax []
and integers:
[1] 10 20 30 40 50
[1] 10
[1] 30
We can use integer vectors with more than one element inside of our index [...]
’s::
[1] 10 30
You can use the :
operator to easily create a sequence of numbers:
[1] 2 3 4
[1] 20 30 40
[1] 10 20 30 40 50
[1] 20 30 40 50
[1] 10
Logical operators always return a logical vector:
[1] FALSE FALSE TRUE TRUE TRUE
[1] TRUE TRUE FALSE FALSE FALSE
[1] FALSE FALSE TRUE FALSE FALSE
[1] TRUE TRUE FALSE TRUE TRUE
The %in%
operator asks if the first set of numbers can be found in the second:
[1] TRUE
[1] TRUE FALSE
The !
operator negates (flips) each value of a logical vector:
[1] FALSE
[1] TRUE TRUE FALSE FALSE FALSE
So how can we combine logical comparisons with indexing?
[1] 30 40 50
[1] 10 20
You can get fancy…
[1] 10 20 30 40 50
What happened there? If you need help figuring it out, look up the %%
(modulo) operator on the help panel.
[1] 10 20 30 40 50
[1] 10 20 100 40 50
[1] 10 1 2 40 50
So how can you shift your thinking to get moving again when you’re stuck and frustrated?