OP Blog 3: Vectors

In this module on R, the element of vectors is introduced. A vector is a sequence of elements of the same data type. It is created using the c() function. You can store a vector into a variable, for example: “numbers <– c(12, 13, 14)”. You can even use the names() function to name the elements in your vector (see the first image for examples of this). To keep track of it all, the str() function is useful to actually view the structure and the attributes of each vector and variable. Also interesting is that when you really think about it, all variables with only one element, are also vectors containing one element. Checking the length of a vector is very easily done by using the length([name of vector]) function. It is important to keep in mind that a vector can only hold elements of the same type, in comparison to lists, which can hold different data types.

The next section in this module talks about making calculations with vectors containing more than one element. Simple calculations such as multiplication, subtraction,… can easily be done by calling them in combination with the name of the vector. The operation then counts for all the elements in the vector. You can also make calculations using two vectors of the same length, as is shown in the second image. The sum() function calculates the total of all the elements in the vector. You can also compare vectors using operators such as “<”, “>” and “=”. The result will be “TRUE” or “FALSE”.

The last section of this module talks about vector subsetting. As the name reveals, it basically comes down to selecting parts of your vector to end up with a new vector, which is a subset of the original vector. To get to one of the elements in a vector, you simply use the name of the vector, followed by the number of its position in square brackets. For example: vector[1] to get to the first element. If the element has a name, it is also kept. You can also use the names instead of the index [1] to get to the element. To select more elements and put them in another vector, you can use a vector too. For example: b <–a[c(1,5)] takes the first five elements of vector “a” and stores them in vector “b”. The same can also be done with named vectors. To delete one element of the vector you can use [-1] to delete the first element of the vector.

The exercises in this module were a lot tougher. The learning curve is quite steep sometimes, and as I am not the most logical thinker, I did have some difficulties with the last exercises. I am still enjoying it, but find that some additional hints might not go amiss.

Leave a comment