Statistics and Data Science with R Part -2
Statistics and Data Science with R Part -2
and
Data Science with R
Example:
Switch Statement
In R, the switch statement is a type of conditional day <- 3
control flow that selects one of several code blocks to
execute based on the value of a specified expression. weekday <- switch(
It's particularly useful when you have multiple cases to
evaluate against a single expression. day,
"Monday",
Syntax: "Tuesday",
switch(EXPR, CASE1, CASE2, ..., CASEn, default) "Wednesday",
"Thursday",
"Friday",
"Weekend"
)
print(weekday)
Loop
Loops are used to repeatedly execute a block of code until a specified condition is met.
Loop
In R, functions are blocks of reusable code designed to perform a specific task. They allow you to encapsulate a
set of operations into a single unit that can be called multiple times with different inputs.
Functions
User-defined
Built-in functions
functions
User Define Function
User-defined functions in R allow you to create your # Function to calculate the square of a
own functions to perform specific tasks or operations. number
These functions encapsulate a set of operations or square <- function(x) {
algorithms you can reuse multiple times with different
return(x^2)
inputs. Creating user-defined functions helps
modularize code, enhance readability, and promote }
code reusability.
# Calling the function with an argument
Syntax: result <- square(5)
function_name <- function(arg1, arg2, ...) print(result)
{
# Code block specifying the operations to be
performed
# Use 'return()' to specify the output of the function
return(output)
}
Scope of Variables # Global variable
global_var <- "I am global"
Variables in R can have different scopes:
my_function <- function() {
• Global Scope: Variables defined in the global # Local variable
environment.
local_var <- "I am local"
• Local Scope: Variables defined inside functions or
print(local_var)
loops.
}
my_function()
print(global_var)
print(local_var) # Error: object
'local_var' not found
Connect
@Grant-Thornton-Bharat-LLP @GrantThorntonBharat @Grantthornton_bharat @GrantThorntonIN @GrantThorntonBharatLLP [email protected]
with us