R can be used as a calculator. The basic arithmetic operators are:
+
(addition)-
(subtraction)*
(multiplication)/
(division)^
(exponentiation)Using above operators in R.
# addition
5 + 8
## [1] 13
# substraction
8 - 7
## [1] 1
# multiplication
5 * 3
## [1] 15
# divison
15/5
## [1] 3
# exponentiation
4^2
## [1] 16
# modulo: returns the remainder of the division of 9/2
9 %% 2
## [1] 1
Note that, in R, ‘#’ is used for adding comments to explain what the R code is about.
# logarithms base 2 of x=10
log2(10)
## [1] 3.321928
# logaritms base 10 of x=10
log10(10)
## [1] 1
# Exponential of x=10
exp(10)
## [1] 22026.47
# cosine of x=60
cos(60)
## [1] -0.952413
# sine of x=60
sin(60)
## [1] -0.3048106
# tangent of x=60
tan(60)
## [1] 0.3200404
# absolute value of x=-5
abs(-5)
## [1] 5
# square root of x=16
sqrt(16)
## [1] 4
A variable can be used to store a value. For example, the R code below will store the price in a variable, say “price”:
# price = 7 INR
price <- 7
# or use this
price = 7
Important Notes
<-
or =
for variable assignments.To print the value of the created object, just type its name:
price
## [1] 7
# or use the function print()
print(price)
## [1] 7
R saves the object price
(also known as a variable) in memory. It’s possible to make some operations with it.
# Multiply price by 3
3 * price
## [1] 21
You can change the value of the object:
# change the value
price <- 8
# print again
price
## [1] 8
The following R code creates two variables holding the width and the height of a rectangle. These two variables will be used to compute teh area of the rectangle.
# height of a rectangle
height <- 10
# width of a rectangle
width <- 5
# area of rectangle
area <- height*width
area
## [1] 50