Day2 Learning Notes : Vectorized Operations

Many operations in R are vectorized, meaning that operations occur in parallel in certain R objects. This allows you to write code that is efficient, concise, and easier to read than in non-vectorized languages.

The simplest example is when adding two vectors together.

Natural, right? Without vectorization, you’d have to do something like

If you had to do that every time you wanted to add two vectors, your hands would get very tired from all the typing.

Another operation you can do in a vectorized manner is logical comparisons. So suppose you wanted to know which elements of a vector were greater than 2. You could do the following.

Here are other vectorized logical operations.

Notice that these logical operations return a logical vector of TRUE and FALSE.
Of course, subtraction, multiplication and division are also vectorized.

 

 

Vectorized Matrix Operations

Matrix operations are also vectorized, making for nicely compact notation. This way, we can do element-by-element operations on matrices without having to loop over every element.

 

 

Copied from R Programming for Data Science – Roger D. Peng

Leave a Reply

Your email address will not be published. Required fields are marked *