R allows you to do many vector operations from your Linear Algebra class with easy. Many operators are element wise such as plus and minus. There are also function like sqrt
that can apply element-wise. In this article, we will see how to do vector arithmetic in R.
The first thing to note, is that if you have two vectors, you can use normal math operations on the two.
x = c(1, 2, 3, 4)
y = c(4, 5, 6, 7)
x + y
# [1] 5 7 9 11
x - y
# [1] -3 -3 -3 -3
You can also do operations with a vector in a scalar.
x = c(1, 2, 3, 4)
x + 2
# [1] 3 4 5 6
x * 2
# [1] 2 4 6 8
The finaly thing we will look at is some element-wise methods you can use. We will look at sqrt
and log
, but there are more in R.
x = c(1, 2, 3, 4)
sqrt(x)
# [1] 1.000000 1.414214 1.732051 2.000000
log(x)
# [1] 0.0000000 0.6931472 1.0986123 1.3862944