Tuesday, October 30, 2018

R - Vector Arithmetic

No comments
So far in our earlier posts we have seen how to create vectors and various operations on vectors like sorting. In this post we will learn to do arithmetic operations on vectors and see how these are helpful for data analysis.

In R, arithmetic operations on vectors occur element-wise. For example, we have a vector say height in inches and suppose we want to convert them to centimeters , then we multiply the heights vector with 2.54 as show below and the resultant vector shows the heights in centimeters.
> heights <- c(69,62,66,70,70,73,67,73,67,70)
>heights*2.54


Similarly we can perform other operations like subtraction, addition , division  etc. The elementary arithmetic operators are the usual +, -, *, / and ^ for raising to a power. In addition all of the common arithmetic functions are available. log, exp, sin, cos, tan, sqrt, and so on, all have their usual meaning. max and min select the largest and smallest elements of a vector respectively. range is a function whose value is a vector of length two, namely c(min(x), max(x)).length(x) is the number of elements in x, sum(x) gives the total of the elements in x, and prod(x) their product.If we have two vectors of same length, these operations are more powerful .The operator used (+ , - , / etc) is applied entry by entry in these two vectors .


Vectors occurring in the same expression need not all be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression.Suppose we have a dataset showing the murders per state and the population of that state , to calculate the murder rate(murders for every 100,000 people) for each state all we have to do is:
>murder_rate <- murders$total/murders$population * 100000



We can use these tools to analyze murder rate of all the states, the average murder rate in a country and see which states are safer by applying the sort functions.Refer the R-Manual for documentation on  arithmetic operators and their usage .

No comments :

Post a Comment