In R, we can assign integer and floating point values to variables directly. The mathematical operations can be performed with variables and operators exactly similar to languages like C, C++, java, python and perl. We have already performed a simple operation c = a+b in the previous section.
For example, we can perform the operation $$ c = \frac{(a + b)}{(a \times b)}$$ by assigning values directly at declaration
> a = 7.5 > b = 6 > c = (a+b)/(a*b) > c
'+' for addition '-' for subtraction '*' for multiplication '/' for divisionIn another example, we apply the formula $$y = 1.0 + {\large (\frac{z}{r})}^{0.38} $$ as,
> z = 22.9 > r = 6.7 > y = 1.0 + (z/r)^0.38 > y
In order to carry out certain standard mathematical operations, R has internal library functions. In programming languages, a function is a collection of code statements that can perform a task. A functtion can take one or more input parameter values, and should give an output result.
For example, if we want to find the natural logarithm of a variable x, we can call the function called log as follows:> x = 42.5 > y = log(x) > y
In the above R codelines, variable x is assigned a value of 42.5. The function call y = log(x) passes the value of x to the function and the value returned by the function is assigned to the variable y. When we print y, we get 3.749504, which is the natural logarithm of 42.5.
---------------------------------------------- Function name Description ---------------------------------------------- abs(x) absolute value sqrt(x) square root ceiling(x) ceiling(3.475) is 4 floor(x) floor(3.475) is 3 trunc(x) trunc(5.99) is 5 round(x, digits=n) round(3.475, digits=2) is 3.48 signif(x, digits=n) signif(3.475, digits=2) is 3.5 cos(x),sin(x),tan(x) Triginomteric sine, cosine and tan functions acos(x),asin(x),atan(x) arcsine, arccosine and arctangent functions log(x) natural logarithm log10(x) common logarithm log2(x) logarithm to the bse of 2 exp(x) exponential of x -----------------------------------------------Let us now translate some mathematical expressions into R code lines: Example 1 : $$ Q = A~log(m^2 + n^2) $$
> A = 120.5 > m = 2.0 > n = 3.2 > > Q = A * log(m^2 + n^2) > > Q
> a = 33.5 > b = 50.0 > x = 4.1 > l = 2.3 > > M = (a/(a+b)) * sin(x/l) * cos(x/l) > > M
> z = 22.9 > r = 6.7 > y = sqrt(1.0 + (z/r)^0.38) > y