Document (1)
Document (1)
1. Overview of R
Features:
Objects in R:
Reading Data:
Writing Data:
Conditional Statements:
Loops:
5. Functions
Syntax:
Return(result)
Example:
Return(x + y)
Add(3, 5) # Output: 8
6. Scoping Rules
Lexical Scoping:
Dynamic Scoping:
Date Class:
Time Class:
8. Loop Functions
9. Debugging Tools
10. Simulation
Generating Random Numbers:
Random Sampling:
Tools:
1. Overview of R
What is R?
Features:
RStudio IDE:
Data Types
Comp <- 2 + 3i
Objects
Reading Data
Raw Input:
Values <- scan(what = integer())
Writing Data
To CSV:
Write.csv(data, “output.csv”)
To Text File:
4. Control Structures
Conditional Statements
If and else:
X <- 10
If (x > 5) {
} else {
Ifelse:
Loops
For loop:
For (I in 1:5) {
Print(i)
While loop:
I <- 1
While (I <= 5) {
Print(i)
I <- I + 1
Repeat loop:
I <- 1
Repeat {
If (I > 5) break
Print(i)
I <- I + 1
5. Functions
Defining Functions
Syntax:
# Function body
Return(result)
Example
Return(x^2)
Square(4) # Output: 16
6. Scoping Rules
Lexical Scoping:
X <- 10
Return(x)
My_func() # Output: 10
8. Loop Functions
Apply:
Lapply:
Sapply:
Tapply:
Mapply(rep, 1:3, 3)
9. Debugging Tools
Traceback:
Traceback()
Debug:
Debug(my_function)
Browser:
Browser()
Recover:
Options(error = recover)
10. Simulation
Random Numbers:
Rprof(“profile.out”)
Rprof(NULL)
summaryRprof(“profile.out”)
Optimization Tips:
What is R?
R is like a calculator but much more powerful. It can handle complex data
analysis, generate beautiful graphs, and automate tasks.
X <- 1:10
Y <- x^2
Data Types
1. Numeric:
X <- 10.5
2. Integer:
Y <- as.integer(7)
3. Character:
Z <- “Hello”
4. Logical:
5. Complex:
Comp <- 2 + 3i
Print(vec) # Output: 1 2 3 4
Print(mat)
Print(lst)
Print(df)
3. Reading and Writing Data
Reading Data
1. From CSV:
2. Raw Input:
Writing Data
1. To CSV:
Conditional Statements
1. If and else:
X <- 10
If (x > 5) {
} else {
Loops
1. For Loop:
For (I in 1:5) {
Print(i)
}
2. While Loop:
I <- 1
While (I <= 5) {
Print(i)
I <- I + 1
3. Repeat Loop:
I <- 1
Repeat {
Print(i)
If (I == 5) break
I <- I + 1
4. Functions
1. Defining a Function:
Square(4) # Output: 16
Return(paste(“Hello,”, name))
5. Scoping Rules
Lexical Scoping:
R searches for a variable in the environment where the function was defined,
not where it’s called.
X <- 10
X <- 20
Return(x)
My_function() # Output: 20
Global Assignment:
X <- 5
X <<- 10
My_function()
Print(x) # Output: 10
7. Loop Functions
1. Apply:
2. Lapply:
3. Sapply:
1. Traceback:
Traceback()
2. Debug:
Debug(square)
Square(4)
3. Browser:
Browser()
Return(x^2)
My_function(4)
9. Simulation
2. Random Sampling:
Rprof(“profile.out”)
Rprof(NULL)
summaryRprof(“profile.out”)
2. Optimization:
X <- 1:10000