Basic Functions in R

Sameer Mathur

1. BASIC ARITHMETIC OPERATIONS

R can be used as a calculator. The basic arithmetic operators are:

  1. + (addition)
  2. - (subtraction)
  3. * (multiplication)
  4. / (division)
  5. ^ (exponentiation)

Type directly the command


1a. Addition

# addition
5 + 8
[1] 13


1b. Substraction

# substraction
8 - 7
[1] 1


1c. Multiplication

# multiplication
5 * 3
[1] 15


1d. Division

# divison
15/5
[1] 3

1e. Exponent

# exponentiation
4^2
[1] 16

1f. Remainder of division

# 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.

2. BASIC ARITHMATIC FUNCTIONS

2a. Logarithms and Exponentials

# 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

2b. Trigonometric functions

# 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

2c. Other mathematical functions

# absolute value of x=-5
abs(-5) 
[1] 5
# square root of x=16
sqrt(16) 
[1] 4

3. ASSIGNING VALUES TO VARIABLES

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 
price <- 7
# or use this
price = 7

Important Notes

  1. Note that, it's possible to use <- or = for variable assignments.

  2. Note that, R is case-sensitive. This means that Price is different from price.

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 <- 5
# print again
price
[1] 5

The following R code creates two variables holding the width and the height of a rectangle. These two variables will be used to compute the 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