0% found this document useful (0 votes)
2 views

Functions

wdb

Uploaded by

gvhvardhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Functions

wdb

Uploaded by

gvhvardhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Functions are useful when you want to perform a certain task multiple times.

A
function accepts input arguments and produces the output by executing valid R
commands that are inside the function. In R Programming Language when you are
creating a function the function name and the file in which you are creating the
function need not be the same and you can have one or more functions in R.
Table of Content
 Function in R Programming
 Types of Function in R Language
 Built-in Function in R Programming Language
 User-defined Functions in R Programming Language
 R Function Example
Function in R Programming
Functions are created in R by using the command function(). The general structure
of the function file is as follows:

Functions in R Programming

Note: In the above syntax f is the function name, this means that you are creating a
function with name f which takes certain arguments and executes the following
statements.
Types of Function in R Language
1. Built-in Function: Built-in functions in R are pre-defined functions that are
available in R programming languages to perform common tasks or operations.
2. User-defined Function: R language allow us to write our own function.
Built-in Function in R Programming Language
Here we will use built-in functions like sum(), max() and min().
# Find sum of numbers 4 to 6.
print(sum(4:6))

# Find max of numbers 4 and 6.


print(max(4:6))

# Find min of numbers 4 and 6.


print(min(4:6))
output
[1] 15[1] 6[1] 4

Other Built-in Functions in R


Functions Syntax

Mathematical Functions

a. abs() calculates a number’s absolute value.

b. sqrt() calculates a number’s square root.

c. round() rounds a number to the nearest integer.

d. exp() calculates a number’s exponential value

which calculates a number’s natural


e. log()
logarithm.

calculates a number’s cosine, sine, and


f. cos(), sin(), and tan()
tang.

Statistical Functions

A vector’s arithmetic mean is determined


a. mean()
by the mean() function.

A vector’s median value is determined by


b. median()
the median() function.

calculates the correlation between two


c. cor()
vectors.

calculates the variance of a vector and


d. var() calculates the standard deviation of a
vector.
Functions Syntax

Data Manipulation Functions

a. unique() returns the unique values in a vector.

b. subset() subsets a data frame based on conditions.

groups data according to a grouping


c. aggregate()
variable.

uses ascending or descending order to sort


d. order()
a vector.

File Input/Output Functions

a. read.csv() reads information from a CSV file.

b. Write.csv() publishes information to write a CSV file.

c. Read. table() reads information from a tabular.

d. Write.table() creates a tabular file with data.

User-defined Functions in R Programming Language


R provides built-in functions like print(), cat(), etc. but we can also create our own
functions. These functions are called user-defined functions.
Example
# A simple R function to check
# whether x is even or odd

evenOdd = function(x){
if(x %% 2 == 0)
return("even")
else
return("odd")
}

print(evenOdd(4))
print(evenOdd(3))
output

[1] "even"
[1] "odd"
R Function Example
Single Input Single Output
Now create a function in R that will take a single input and gives us a single
output.
Following is an example to create a function that calculates the area of a circle
which takes in the arguments the radius. So, to create a function, name the function
as “areaOfCircle” and the arguments that are needed to be passed are the “radius”
of the circle.
# A simple R function to calculate
# area of a circle

areaOfCircle = function(radius){
area = pi*radius^2
return(area)
}

print(areaOfCircle(2))

output

12.56637
Multiple Input Multiple Output
Now create a function in R Language that will take multiple inputs and gives us
multiple outputs using a list.
The functions in R Language take multiple input objects but returned only one
object as output, this is, however, not a limitation because you can create lists of all
the outputs which you want to create and once the list is created you can access
them into the elements of the list and get the answers which you want.
Let us consider this example to create a function “Rectangle” which takes “length”
and “width” of the rectangle and returns area and perimeter of that rectangle. Since
R Language can return only one object. Hence, create one object which is a list that
contains “area” and “perimeter” and return the list.
# A simple R function to calculate
# area and perimeter of a rectangle

Rectangle = function(length, width){


area = length * width
perimeter = 2 * (length + width)
# create an object called result which is
# a list of area and perimeter
result = list("Area" = area, "Perimeter" = perimeter)
return(result)
}

resultList = Rectangle(2, 3)
print(resultList["Area"])
print(resultList["Perimeter"])

otput

$Area
[1] 6
$Perimeter
[1] 10

Inline Functions in R Programming Language


Sometimes creating an R script file, loading it, executing it is a lot of work when
you want to just create a very small function. So, what we can do in this kind of
situation is an inline function.
To create an inline function you have to use the function command with the
argument x and then the expression of the function.
# A simple R program to
# demonstrate the inline function

f = function(x) x^2*4+x/3

print(f(4))
print(f(-2))
print(0)

output

65.33333
15.33333
0
Passing Arguments to Functions in R Programming Language
There are several ways you can pass the arguments to the function:
 Case 1: Generally in R, the arguments are passed to the function in the same
order as in the function definition.
 Case 2: If you do not want to follow any order what you can do is you can pass
the arguments using the names of the arguments in any order.
 Case 3: If the arguments are not passed the default values are used to execute
the function.
Now, let us see the examples for each of these cases in the following R code:
A simple R program to demonstrate
# passing arguments to a function

Rectangle = function(length=5, width=4){


area = length * width
return(area)
}

# Case 1:
print(Rectangle(2, 3))

# Case 2:
print(Rectangle(width = 8, length = 4))

# Case 3:
print(Rectangle())

OUTPUT
6
32
20

You might also like