Hands-On Geospatial Analysis with R and QGIS
上QQ阅读APP看书,第一时间看更新

Basic operations with vector

Suppose the prices of three commodities, namely potatoes, rice, and oil were $10, $20, and $30 respectively in January 2018, denoted by the vector jan_price, and the prices of all these three elements increased by $1, $2, and $3 respectively in March 2018, denoted by the vector increase. Then, we can add two vectors mar_price and increase to get the new price as follows:

jan_price = c(10, 20, 30)
increase = c(1, 2, 3)
mar_price = jan_price + increase

To see the contents of mar_price, we just need to write it and then press Enter:

mar_price

We now see that mar_price is updated as expected:

[1] 11 22 33

Similarly, we can subtract and multiply. Remember that R uses element-wise computation, meaning that if we multiply two vectors which are of the same size, the first element of the first vector will be multiplied by the first element of the second vector, and the second element of the second vector will be multiplied by the second element of the second vector, and as such:

x = c(10, 20, 30)
y = c(1, 2, 3)
x * y

The result of this multiplication is this:

[1] 10 40 90

If we multiply a vector with multiple values by a single value, that latter value multiplies every single element of the vector separately. This is demonstrated in the following example:

x * 2

We can see the output of the preceding command as follows:

[1] 20 40 60

As a vector does element-wise computation, if we check for any condition, the condition will be checked for each element. Thus, if we want to know which values in x are greater than 15:

x > 15

As the second and third elements satisfy this condition of being greater than 15, we see TRUE for these positions and FALSE for the first position as follows:

[1] FALSE TRUE TRUE

Indexing in R or the first element of any data type starts with 1; thus, the third or fourth element in R can be accessed with index 3 or 4. We need to access any particular index of a variable with a variable name followed by the index inside []. Thus, the third element of x can be accessed as follows:

x[3]

By pressing Enter after x[3], we see that the third element of x is this:

30

If we want to select all items but the third one, we need to use - in the following way:

x[-3]

We now see that x has all of the elements except the third one:

[1] 10 20