Introduction

A statement is a piece of code, that is complete syntactically.

# this is a statement too
9+2
## [1] 11
# syntax complete statement
rnorm(10,mean=10,sd=2)
##  [1] 10.549262 12.968087  9.857696  9.140546  6.730251  7.906343  8.666414
##  [8] 10.463023  5.519568  8.031606

With growing confidence, you can write multiple statements in a single line, separated by ;.

a <- 2; b <- 2;
a
## [1] 2
b
## [1] 2

Function

Once you get going, you will end up with too many lines of code and you will also notice that you might be repetitively using the same statement(s). This calls for code organization and it can be doing using function(s).

A function is a collection of statements to perform very specific tasks, most of the times geared towards a specific objective. Lets define our first function:

my_addition_function <- function(a,b){
  # this function adds two objects and returns them
  
  return(a+b)
}
my_addition_function(23,39)
## [1] 62

Properties of a function

  • A meaningful name that does not clash with in-built functions of R. (my_addition_function)
  • You are creating telling R that create my_addition_function based on the template of function() and it will be expecting two arguments (optional) a & b.
  • specifying a return is optional as well.
  • Always call a function with its name followed by (), otherwise R will print the code inside the function.

A function with that does not return anything:

# this function adds two objects and returns them
my_addition_function <- function(a,b){
  # still performs the addition
  a+b
  return()
}
my_addition_function(23,39)
## NULL
my_addition_function
## function(a,b){
##   # still performs the addition
##   a+b
##   return()
## }

Can you write a better version of my_addition_function()?

 

Introduction to R by Dr. Sarath Chandra Dantu

This course material is available under a Creative Commons BY-SA license (CC BY-SA) version 4.0