2.2 Vector operations
A lot of data manipulation in R is based on logical checks like the ones shown above. We can take these one step further to actually perform what one might think of as a query.
For example, we can reference specific elements of vectors directly. Here, we specify that we want to print the third element of a
.
## [1] 3
We might want to store that value to a new object f
that is easier to read and type out.
Important
If it is not yet obvious, we have to assign the output of functions to new objects for the values to be usable in the future. In the example above, a
is never actually changed. This is a common source of confusion early on.
Going further, we could select vector elements based on some condition. On the first line of code, we tell R to show us the indices of the elements in vector b
that match the character string c
. Out loud, we would say, “b
where the value of b
is equal to c
” in the first example. We can also use built-in R functions to just store the indices for all elements of b
where b
is equal to the character string “c
”.
## [1] c
## Levels: a b c d e
## [1] 3
Perhaps more practically speaking, we can do elementwise operations on vectors easily in R. Here are a bunch of different things that you might be interested in doing with the objects that we’ve created so far. Give a few of these a try. Perhaps more practically speaking, we can do elementwise operations on vectors easily in R. Give a few of these a shot.
a * .5 # Multiplication
a + 100 # Addition
a - 3 # Subtraction
a / 2 # Division
a^2 # Exponentiation
exp(a) # Same as "e to the a"
log(a) # Natural logarithm
log10(a) # Log base 10
If we change b to character
, we can do string manipulation, too!
We can append text. Remember, the examples below will just print the result. We would have to overwrite b
or save it to a new object if we wanted to be able to use the result somewhere else later.
## [1] "aAAAA" "bAAAA" "cAAAA" "dAAAA" "eAAAA"
## [1] "AAAAa" "AAAAb" "AAAAc" "AAAAd" "AAAAe"
## [1] "AAAA--a" "AAAA--b" "AAAA--c" "AAAA--d" "AAAA--e"
## [1] "a" "b" "AAAA" "d" "e"
## [1] "AAAAa" "AAAAb" "AAAAc" "AAAAd" "AAAAe"
## [1] "a" "b" "c" "d" "e"
We can check how many elements are in a vector.
## [1] 5
## [1] 1 2 3 4 5
And we can do lots of other nifty things like this. We can also bind multiple vectors together into a rectangular matrix
. Say what?