0% found this document useful (0 votes)
2 views34 pages

Unit 2 R

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views34 pages

Unit 2 R

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 2

Readingand WritingFiles
R can read data from a variety of file formats—for example, files created as text, or in Excel, SPSS or Stata.
•We will mainly be reading files in text format .txt or
.csv (comma-separated, usually created in Excel).
•To read an entire data frame directly, the external file will normally have a special form

The first line of the file should have a name for each
variable in the data frame.
•Each additional line of the file has as its first item a row label and the values for each variable.

Code to import the file in to the software:


myData = [Link]("[Link]", header =
FALSE)print(myData)

2 R PROGRAMMING 2024
3 R PROGRAMMING 2024
To find out what your current working directory is, type
•getwd()
It’s also possible to write csv files using the functions [Link]().
The syntax is as follow:
[Link](my_data, file = "my_data.csv")

4 Presentation title 20XX


R Conditional Statements
The if Statement The If Else Statement
An "if statement" is written with The else keyword catches anything which
the if keyword, and it is used to specify a isn't caught by the preceding conditions:
block of code to be executed if a condition
is TRUE: Example:

Example:

Output: Output:
R Conditional Statements
The Else If Statement Nested If Statements
The else if keyword is R's way of saying You can also have if statements
"if the previous conditions were not true, inside if statements, this is
then try this condition": called nested if statements.
Example:
Example:

Output:
Output:
R Conditional Statements
The S w i t c h S t a t e m e n t
Syntax:
Definition: switch(expression,
Is a substitute for long if statements that value1={ Code to execute when expression equals value1},
compare a variable to several integral values. Is Value2={Code to execute when expression equals value2},
multiway branch statement. Used to select one Default={ Code to execute when none of the values match}
of several code blocks to execute based on a
)
specified condition.

x <- "B"
OUTPUT
result <- switch(x,
"A" = "Apple",
"B" = "Banana", [1] "Banana"
"C" = "Cherry",
"Unknown" # Default case if no match
)

print(result)
R Looping Statements
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more
readable.
R has two loop commands:
• while loops
• for loops

R While Loops Example:


With the while loop we can execute a set
of statements as long as a condition is
TRUE:

In the example given, the loop will


continue to produce numbers ranging
from 1 to 5. The loop will stop at 6
because 6 < 6 is FALSE. Output:
R Looping Statements
Break Next
With the break statement, we can stop the With the next statement, we can skip an
loop even if the while condition is TRUE: iteration without terminating the loop:

Example: Example:

Output: Output:
R Looping Statements
R For Loop
A for loop is used for iterating over a sequence:

Example: Example: Example:

Output: Output: Output:


R Looping Statements
REPEAT STATEMENT
Syntax:
Repeat a block of code multiple number of times. It
repeat{
executes same code again and again until break statement
Block statements
is found. An infinite loop in R can be created
Example: very easily
Example: Example:
with the help of the Repeat loop. if(condition){
break
}
}
count<-1
Repeat
{ cat("Count:",count,"\n") :
count<-count+1 Output
if(count>5) Count: 1
{ Count: 2
break Count: 3
} Count: 4
} Count: 5
R Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.

Types of Function in R Language


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.
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().
R Functions
Built-In-Functions
1. Mathematical Functions
abs(), sqrt(), log(), exp(), round(), ceiling(), floor(), sin(), cos(), tan(), etc.

2. Statistical Functions
mean(), median(), sd(), var(), sum(), prod(), min(), max(), etc.

3. Character/String Functions
nchar(), toupper(), tolower(), substr(), paste(), grep(), gsub(), strsplit(), etc.

4. Sequence and Repetition Functions


seq(), rep(), sample(), rev(), etc.

5. Data Manipulation Functions


length(), sort(), unique(), table(), append(), cbind(), rbind(), etc.

6. Logical and Comparison Functions


any(), all(), which(), [Link](), [Link](), identical(), etc.

7. Apply Functions (Functional Programming)


apply(), lapply(), sapply(), tapply(), mapply(), vapply(), etc.
R Functions
Built-In-Functions
R Functions
Built-In-Functions
R Functions Built-In-Functions
R STRING FUNCTIONS
Functions
R Functions
User-defined Functions in R Programming Language:
We can also create our own functions. These functions are called user-defined functions.

[Link] a Function:
Output:
Syntax:
add_numbers<-function(a,b){
Function_name<-function(arg1,arg2,….){
result<-a+b
#Function body: code to perform the task
Return(result)
return(result)}
}

[Link] a Function:

Output:
Syntax: result<-add_numbers(3,5)
Function name(Parameters if any)
R Functions
User-defined Functions in R Programming Language:
We can also create our own functions. These functions are called user-defined functions.

Call a Function
To call a function, use the function name followed by parenthesis, like evenodd():

Arguments
Information can be passed into functions as arguments.
R Functions
Default Parameter Value
If we call the function without an argument, it uses the default value:
R Functions
To create a function with multiple parameters:

# Define a function that calculates the area of a rectangle


calculate_area <- function(length, width) {
area <- length * width
return(area)
}

# Call the function with example values


length <- 10
width <- 5
result <- calculate_area(length, width)

# Print the result


cat("The area of the rectangle is:", result, "\n")
Timings and Visibility (Scope of a Variable)
The location where we can find a variable and also access it if required is called the
scope of a variable.
There are mainly two types of variable scopes:

Global Variables: Global variables are those variables that exist throughout the
execution of a program. It can be changed and accessed from any part of the
program.

Local Variables: Local variables are those variables that exist only within a certain
part of a program like a function and are released when the function call ends.
Timings and Visibility (Scope of a Variable)
Timings and Visibility (Scope of a Variable)
R EXCEPTIONS
1. Runtime error occurs based on conditions at the run time of a program
2. Ex: Divided by zero, file not found, array out of range
3. Exceptions are a mechanism for handling runtime errors or exceptional situations that may occur during the
execution of a program.
4. Using tryCatch
R EXCEPTIONS
.try(): continue with the execution of the program even when error
try() occurs
3 methods in tryCatch()
•tryCatch(): it helps to handle the conditions and control what
happens based on the conditions.
tryCatch() • withCallingHandlers(): it is an alternative to tryCatch() that
takes care of the local handlers.
try()
withCallingHandlers()
EXAMPLE

print('start of code’)
result<-try(sqrt('text’))
print("this will be printed because try() does not stop execution")
if(inherits(result,'try-error’))
{ print("Handled error: invalid input for sqrt()")}
print('Execution continues after try block')
OUTPUT
[1] "start of code"
Error in sqrt("text") : non-numeric argument to mathematical function
[1] "this will be printed because try() does not stop execution"
[1] "Handled error: invalid input for sqrt()" [
1] "Execution continues after try block"
R EXCEPTIONS
trycatch()
EXAMPLE
tryCatch({
print("Start of code")
x<-log(-1)
print("This wont be printed. trycatch skips this statement by default")},
warning=function(x){
print("Custom warning message:Log of a negative number")})
print("Execution continues after trycatch block")

OUTPUT
1] "Start of code"
[

[1] "Custom warning message:Log of a negative number“


[1] "Execution continues after trycatch block"
R EXCEPTIONS
EXAMPLE
withCallingHandlers({
print("Start of code")
x<-log(-1)
print("This will be printed following the logging of warning")
},warning=function(w){
print("This will be printed. withcallingHandlers executes this statement as log() is non-fatal warning")
})
print("Execution continues after withCallingHandlers block")

OUTPUT
[1] "Start of code"
[1] "This will be printed. withcallingHandlers executes this statement as log() is non-fatal warning"
[1] "This will be printed following the logging of warning"
[1] "Execution continues after withCallingHandlers block"
Warning message:
In log(-1) : NaNs produced
R Exceptions
• The exception handling facilities in R are provided through two mechanisms.
• Functions such as stop or warning can be called directly or options such as “warn” can be used to
control the handling of problems.
Syntax:
check = tryCatch(
{
expression
},
warning = function(w)
{
code that handles the warnings
},
error = function(e)
{
code that handles the errors
},
finally = function(f)
{
clean-up code
})
R Exceptions

• tryCatch(): it helps to handle the conditions and control


what happens based on the conditions.
• withCallingHandlers(): it is an alternative to tryCatch()
that takes care of the local handlers.
TIMING FUNCTIONS
• Timing in R is the amount of time it takes for a particular operation, function or set of
operations to execute in R code.
• It is useful for comparing the performance of algorithms.
• To choose best approach

TIMING FUNCTIONS

[Link]() [Link]() [Link]()


TIMING FUNCTIONS
[Link]()- used to determine current system time
EXAMPLE
OUTPUT
current_time<-[Link]()
[1] "2025-04-04 11:44:30 IST"
print(current_time)

[Link]()- returns the amount of CPU time used by the R process. The [Link]() allows you to
measure the execution time of a specific expression or block of code. Returns object containing
information about usertime,system time and elapsed time.
EXAMPLE
result<-[Link]( {
#Code to measure execution time OUTPUT
for(i in 1:1000000){
sqrt(i) User time: 0.02
} System time: 0
} Elapsed time: 0.03
)cat("User time:",result[1],"\n")
cat("System time:",result[2],"\n")
cat("Elapsed time:",result[3],"\n")
TIMING FUNCTIONS
• [Link]()- returns the amount of CPU time used. Useful for measuring the time taken by overall R session.
• Measuring total time since R started.

EXAMPLE
# Start timing
start_time <- [Link]()

# Simple task: a for loop


for (i in 1:10000000) { OUTPUT
x <- i * 2
user system elapsed
}
0.47 0.08 0.53
# End timing
end_time <- [Link]()

# Time taken
print(end_time - start_time)
TIMING FUNCTIONS

You might also like