官术网_书友最值得收藏!

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
主站蜘蛛池模板: 浦东新区| 武平县| 鱼台县| 海丰县| 射阳县| 增城市| 长沙县| 年辖:市辖区| 盘锦市| 嵊州市| 神农架林区| 渝中区| 拉萨市| 巴青县| 潍坊市| 承德县| 镇远县| 濮阳市| 依安县| 九龙坡区| 景德镇市| 仁布县| 南溪县| 清流县| 英山县| 紫云| 蓬安县| 清水河县| 昭平县| 越西县| 滁州市| 波密县| 宕昌县| 宁德市| 莒南县| 洱源县| 南部县| 仁怀市| 万盛区| 怀集县| 伊宁市|