2) Perform Vector Arithmetic.

This Blog entry is from the Data Structures section in Learn R.

A variety of arithmetic operators can be used against vectors such as:

·         + Addition

·         - Subtraction

·         * Multiplication

·         / Division

·         ^ Power

·         %% mod

In this example, a numeric Vector will be multiplied by 2.  Start by creating a Vector, type:

Multiply <- c(1,2,3,4,5)
create-a-vector-using-the-c-function-ready-for-multiply.png

Run the line of script to console:

create-vector-using-c-function-in-r-console.png

In this example, multiply the vector by 2.   Type:

Multiply * 2
script-to-multiply-a-vector-by-two-in-r.png

Run the line of script to console to write out the new vector:

new-vector-multiplied-by-two-written-to-r-console.png

It can be observed that each position in the vector has been multiplied by the value of 2.  It is also possible to multiple by another vector.  Create another vector by typing:

MultiplyBy <- c(5,4,3,2,1)
create-a-new-vector-that-will-be-used-to-multiply.png

Then multiply the existing vector Multiply by the new vector MultiplyBy by typing:

Multiply * MultiplyBy
a-script-to-multiply-one-vector-by-another.png

Run the line of script to console:

the-multipled-vector-one-by-another-written-to-r-console.png

It can be observed that for each position in the vector, the value in that position has been multiplied by the same position in the other vector.  Think of this as the equivalent of filling down in an Excel spreadsheet.