0% found this document useful (0 votes)
9 views10 pages

Functions: Built-In Functions in R

The document provides an overview of functions in R, including built-in and user-defined functions, as well as conditional statements and loops. It explains how to create functions, use conditional statements like if-else and switch, and iterate through data using for, while, and repeat loops. Additionally, it introduces the apply family of functions for applying operations to data structures efficiently.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

Functions: Built-In Functions in R

The document provides an overview of functions in R, including built-in and user-defined functions, as well as conditional statements and loops. It explains how to create functions, use conditional statements like if-else and switch, and iterate through data using for, while, and repeat loops. Additionally, it introduces the apply family of functions for applying operations to data structures efficiently.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Functions

A function in R is an object containing multiple interrelated statements that are run together in a
predefined order every time the function is called. Functions in R can be built-in or created by
the user (user-defined). The main purpose of creating a user-defined function is to optimize our
program, avoid the repetition of the same block of code used for a specific task that is frequently
performed in a particular project, prevent us from inevitable and hard-to-debug errors related to
copy-paste operations, and make the code more readable.
Built-in Functions in R
There are plenty of helpful built-in functions in R used for various purposes. Some of the most
popular ones are:
 min(), max(), mean(), median() – return the minimum / maximum / mean / median value
of a numeric vector, correspondingly
 sum() – returns the sum of a numeric vector
 range() – returns the minimum and maximum values of a numeric vector
 abs() – returns the absulute value of a number
 str() – shows the structure of an R object
 print() – displays an R object on the console
 ncol() – returns the number of columns of a matrix or a dataframe
 length() – returns the number of items in an R object (a vector, a list, etc.)
 nchar() – returns the number of characters in a character object
 sort() – sorts a vector in ascending or descending (decreasing=TRUE) order
Example:

vector <- c(3, 5, 2, 3, 1, 4)

print(min(vector))
print(mean(vector))
print(median(vector))
print(sum(vector))
print(range(vector))
print(str(vector))
print(length(vector))
print(sort(vector, decreasing=TRUE))
print(exists('vector')) ## note the quotation marks

Creating a Function in R
While applying built-in functions facilitates many common tasks, often we need to create our
own function to automate the performance of a particular task. To declare a user-defined function
in R, we use the keyword function. The syntax is as follows:

function_name <- function(parameters){


function body
}

Above, the main components of an R function are: function name, function parameters,
and function body. Let's take a look at each of them separately.

Example :-

circumference <- function(r){


2*pi*r
}
print(circumference(2))

my_function <- function(fname) {


paste(fname, "Griffin")
}

my_function("Peter")
my_function("Lois")
my_function("Stewie")
Conditional Statements (if, if else, switch) in R
Conditional statements are a type of control statement that execute specific blocks of code
depending on the value of a condition.

The Structure of Conditional Statements

1. IF--Else
The general structure is

if (condition) {
true_code_1
} else {
false_code_1
}

 condition is usually a logical statement.


 true_code_1 are the code blocks executed when condition evaluates to TRUE.
 false_code_1 are the code blocks executed when condition evaluates to FALSE.
The else block is optional.

Example :
Example: Checking Even or Odd Numbers

x <- 3
if (x%%2 == 0) {
cat("x is an even number\n")
} else {
cat("x is an odd number\n")
}
#> x is an odd number
2 Using ifelse()

The ifelse() function allows you to select values based on whether a condition
is TRUE or FALSE:

x_type <- ifelse(x%%2 == 0, "even", "odd")


x_type
#> [1] "odd"

3. Multiple Conditions with else if

You can chain multiple conditions using else if:

x <- 9
if (x%%3 == 1) {
cat("The remainder of x divided by 3 is 1.\n")
} else if (x%%3 == 2) {
cat("The remainder of x divided by 3 is 2.\n")
} else {
cat("x is divisible by 3.\n")
}
#> x is divisible by 3.

4. Switch
The switch() function selects and returns a value based on an expression.

Syntax

switch(expression, case1, case2, case3....)

Example:
x <- switch( 3, "first", "second", "third", "fourth" )
print(x)

day <- 3
weekday <- switch(day, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday")
print(weekday)
Repetitive execution: For and While loops
In R programming, we require a control structure to run a block of code multiple times.
There are three types of loops in R programming:
 For Loop
 While Loop
 Repeat Loop
For Loop in R
A for-loop is one of the main control-flow constructs of the R programming language. It is used
to iterate over a collection of objects, such as a vector, a list, a matrix, or a dataframe, and apply
the same set of operations on each item of a given data structure.
Syntax :

for (variable in sequence) {


expression
}

Example

for (x in 1:10) {
print(x)
}

dice <- c(1, 2, 3, 4, 5, 6)

for (x in dice) {
print(x)
}

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
if (x == "banana") {
next
}
print(x)
}

2. While Loop
While loop in R programming language is used when the exact number of iterations of a loop is
not known beforehand. It executes the same code again and again until a stop condition is met.
While loop checks for the condition to be true or false n+1 times rather than n times. This is
because the while loop checks for the condition before entering the body of the loop.

R- While loop Syntax:

while (test_expression) {
statement
update_expression
}

 When the condition is tested and the result is false then the loop is terminated.
 And when the tested result is True, then the loop will continue its execution.
Example :

result <- 1
i <- 1

# test expression
while (i < 6) {
print(result)
# update expression
i=i+1
result = result + 1
}
Assignment:
Write 2 programs to print 1 to 10 number except number 3 using for and while loop
Write a program to print first 20 even number using loop
3. Repeat
Repeat loop in R is used to iterate over a block of code multiple number of times. And also it
executes the same code again and again until a break statement is found.

Syntax :

repeat {
commands
if(condition) {
break
}

Example:

result <- c("Hello World")


i <- 1
# test expression
repeat {
print(result)

# update expression
i <- i + 1
# Breaking condition
if(i >5) {
break
}
}
Apply Functions in R
The R Apply Family is a set of functions in R that allow users to apply a function to elements of
a vector, list, or matrix.
The apply() functions form the basis of more complex combinations and helps to perform
operations with very few lines of code. More specifically, the family is made up of
the apply(), lapply() , sapply(), vapply(), mapply(), rapply(), and tapply() functions.
Use of apply depends on the structure of the data that you want to operate on and the format of
the output that you need.
1. Apply()
The apply() function lets us apply a function to the rows or columns of a matrix or data frame.
This function takes matrix or data frame as an argument along with function and whether it has
to be applied by row or column and returns the result in the form of a vector or array or list of
values obtained.
Syntax:

apply( x, margin, function )


Parameters:

 x: determines the input array including matrix.


 margin: If the margin is 1 function is applied across row, if the margin is 2 it is applied
across the column.
 function: determines the function that is to be applied on input data.
Example :

# create sample data


sample_matrix <- matrix(C<-(1:10),nrow=3, ncol=10)
print( "sample matrix:")
sample_matrix

# Use apply() function across row to find sum


print("sum across rows:")
apply( sample_matrix, 1, sum)
# use apply() function across column to find mean
print("mean across columns:")
apply( sample_matrix, 2, mean)

You might also like