0% found this document useful (0 votes)
0 views190 pages

R Programming Language

R programming language notes prepared for my sem

Uploaded by

logirusiv
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)
0 views190 pages

R Programming Language

R programming language notes prepared for my sem

Uploaded by

logirusiv
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

R Programming Language

1, Explain R Programming Language

🔹 Definition (Write ANY 2–4)

 R is a programming language used for statistical computing and data analysis.


 R is an open-source software used to analyze and visualize data.
 R is a language used for handling data and creating graphs.
 R is a tool used for mathematical and statistical operations.

🔹 Introduction

 R is mainly used for data analysis and statistics


 It is open-source and free to use
 Used by data analysts, researchers, and companies
 Helps to analyze data and create graphs
 Provides many built-in functions

Features of R Programming:

1. Open Source:
o Free to use and modify
2. Powerful Data Handling:
o Can handle large datasets easily
3. Statistical Analysis:
o Supports mean, median, regression, etc.
4. Graphical Representation:
o Creates charts like bar graph, pie chart, scatter plot
5. Extensive Packages:
o Thousands of packages available
6. Cross Platform:
o Works on Windows, Linux, Mac

Advantages

 Easy to learn
 Many built-in functions
 Strong community support
🔹 Disadvantages

 Uses more memory


 Slightly slow

🔹 Basic R Program

a <- 10
b <- 20
sum <- a + b
print(sum)

👉 Output: 30

🔹 Real-Time Example

 R is used in companies to analyze sales data


 Helps to find profit and loss
 Used to create graphs for reports

🔹 Conclusion

 R is a powerful tool for data analysis and visualization


 It is widely used in real-world applications
2, Uses of R (Why R is Used)

 Used for statistical analysis (mean, median, etc.)


 Used for data visualization (graphs and charts)
 Used for handling large datasets
 Used in machine learning and prediction
 Used for report generation and data processing

🔹 Basic R Program

# Finding average
marks <- c(80, 85, 90)
avg <- mean(marks)
print(avg)

👉 Output: 85

🔹 Real-Time Example

 A company uses R to analyze customer data


 Helps to find sales trends and profit
 Used to create graphs for reports

🔹 Conclusion

 R is widely used for data analysis, statistics, and visualization


 It is an important tool in modern data-driven applications
3, Explain RStudio Overview and Working in the Console

🔹 Definition (Write ANY 2–4)

 RStudio is an integrated development environment (IDE) for R programming


 RStudio is used to write, run, and manage R programs
 RStudio provides a user-friendly interface for working with R
 Console is a place where R commands are executed directly

🔹 Introduction

 RStudio is a tool used to work easily with R programming


 It provides different sections like script, console, environment, and plots
 The console is used to execute commands and see output immediately
 It helps beginners to learn and run R programs easily

🔹 RStudio Overview
Main Parts of RStudio:

 Script Editor
o Used to write and save R programs
 Console
o Used to run commands directly
 Environment
o Shows variables and data
 Plots/Files/Packages
o Used to display graphs and manage files

🔹 Working in the Console

 Console is used to enter R commands directly


 Output is shown immediately after execution
 No need to save program to run
 Used for quick testing and calculations
 Each command runs when you press Enter

🔹 Basic R Program (Console Example)


# Using console
a <- 5
b <- 3
result <- a + b
print(result)

👉 Output: 8

🔹 Uses

 Used to write and execute R programs


 Helps in quick calculations in console
 Used to debug and test code
 Helps to visualize data using plots
 Used to manage files and packages

🔹 Real-Time Example

 A student uses RStudio to write code in script editor


 Uses console to check output quickly
 Creates graphs in plots section

🔹 Conclusion

 RStudio makes R programming easy and user-friendly


 Console helps to execute commands quickly and efficiently
4, Explain Operators in R

🔹 Definition (Write ANY 2–4)

 Operators are symbols used to perform operations on variables and values


 Operators help to perform calculations and comparisons
 Operators are used to manipulate data in R
 Operators are used for arithmetic, logical, and other operations

🔹 Introduction

 Operators are used to perform operations in R


 They work on variables and values
 R provides different types of operators
 They are important for calculation and decision making

🔹 1. Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
^ Power x^y
%% Modulus x %% y
%/% Integer Division x %/% y

🔹 Example Program

x <- 10
y <- 3

print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x ^ y)
print(x %% y)
print(x %/% y)
🔹 2. Assignment Operators
Operator Description Example
<- Assign value x <- 5
= Assign value x=5
-> Reverse assign 5 -> x
<<- Global assign x <<- 5
->> Reverse global 5 ->> x

🔹 Example Program

x <- 10
20 -> y

z <- x + y

print(x)
print(y)
print(z)

🔹 3. Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal x >= y
<= Less than or equal x <= y

🔹 Example Program

a <- 10
b <- 5

print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
🔹 4. Logical Operators

Operator Description

& Element-wise Logical AND operator. Returns TRUE if both elements


are TRUE

&& Logical AND operator - Returns TRUE if both statements are TRUE

| Elementwise- Logical OR operator. Returns TRUE if one of the


statements is TRUE

|| Logical OR operator. Returns TRUE if one of the statements is TRUE

! Logical NOT - Returns FALSE if statement is TRUE

🔹 Example Program

x <- 10

print((x > 5) & (x < 20))


print((x > 5) | (x < 5))
print(!(x > 5))

🔹 5. Miscellaneous Operators
Operator Description Example
: Sequence x <- 1:5
%in% Check element x %in% y
%*% Matrix multiplication m1 %*% m2

🔹 Example Program

x <- 1:5
print(x)

print(3 %in% x)

m1 <- matrix(c(1,2,3,4), nrow=2)


m2 <- matrix(c(5,6,7,8), nrow=2)
print(m1 %*% m2)

🔹 Uses

 Used to perform calculations


 Used to compare values
 Used in decision making
 Used to manipulate data
 Used in real-world programs

🔹 Conclusion

 Operators are essential for performing operations and processing data in R


5, Explain Variables in R (REFER NOTE ALSO)

🔹 Definition (Write ANY 3–4)

 Variables are containers used to store data values


 A variable is a name given to store a value in memory
 Variables are used to store and manipulate data in R
 Variables hold different types of values like numbers and text

🔹 Introduction

 Variables are used to store data in R programming


 R does not require declaration of variables
 A variable is created when a value is assigned for the first time
 Variables are important for data analysis and calculations

🔹 Creating Variables in R
Theory Points:

 Variables are created using assignment operator <-


 R does not have a separate command for declaration
 A variable is created when a value is assigned
 = can also be used, but <- is preferred

🔹 Example Program

name <- "John"


age <- 40

name
age
Explanation Points:

 name and age are variables


 "John" and 40 are values
 Values are stored using <- operator
🔹 Assignment Operators (Theory)

 <- is the most commonly used operator


 = can also assign values
 -> assigns value in reverse direction
 <- is preferred in R programming
 <<- is used for global assignment

🔹 Example Program

x <- 10
20 -> y

z <- x + y

print(x)
print(y)
print(z)
Explanation Points:

 x is assigned using <-


 y is assigned using ->
 z stores result of addition

🔹 Print / Output Variables


Theory Points:

 Variables can be printed by just typing the name


 print() function can also be used
 print() is required inside loops {}
 Output is shown immediately in console

🔹 Example Program 1

name <- "John Doe"

name
Explanation:

 Value is printed automatically


🔹 Example Program 2

name <- "John Doe"

print(name)
Explanation:

 print() function displays output

🔹 Example Program 3

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

 Loop prints values from 1 to 10


 print() is required inside loop

🔹 Concatenation in R
Theory Points:

 Concatenation means joining elements


 paste() function is used
 Comma , is used to combine values
 Used to combine text and variables

🔹 Example Program 1

text <- "awesome"

paste("R is", text)


Explanation:

 Combines text and variable

🔹 Example Program 2
text1 <- "R is"
text2 <- "awesome"

paste(text1, text2)
Explanation:

 Combines two variables

🔹 Example Program 3

num1 <- 5
num2 <- 10

num1 + num2
Explanation:

 Numbers are added using +

🔹 Example Program 4

num <- 5
text <- "Some text"

num + text
Explanation:

 Error occurs because number and text cannot be added

🔹 Multiple Variables
Theory Points:

 Same value can be assigned to multiple variables


 Assignment is done in a single line
 Saves time and reduces code
 Useful in data processing

🔹 Example Program

var1 <- var2 <- var3 <- "Orange"


var1
var2
var3
Explanation:

 All variables store same value

🔹 Variable Names (Identifiers)


Theory Points:

 Variables can have short or descriptive names


 Names should be meaningful
 Used to identify stored values
 Must follow certain rules

🔹 Rules for Variable Names

 Must start with a letter


 Can contain letters, digits, underscore (_), and period (.)
 If starts with ., next character should not be a digit
 Cannot start with a number or underscore
 Cannot contain spaces or special symbols
 Variable names are case-sensitive
 Reserved words cannot be used

🔹 Legal Variable Names

myvar <- "John"


my_var <- "John"
myVar <- "John"
MYVAR <- "John"
myvar2 <- "John"
.myvar <- "John"

🔹 Illegal Variable Names

2myvar <- "John"


my-var <- "John"
my var <- "John"
_my_var <- "John"
my_v@ar <- "John"
TRUE <- "John"

🔹 Uses

 Used to store data values


 Helps in calculations
 Used in data analysis
 Makes program easy to understand
 Used in real-world applications

🔹 Real-Time Example

 Store name → name <- "Rahul"


 Store marks → marks <- 90
 Calculate total using variables

🔹 Conclusion

 Variables are essential for storing and managing data in R programming


6, Explain Data Types in R

🔹 Definition (Write ANY 3–4)

 Data type is a classification of data that tells what type of value is stored
 Data types define whether a value is numeric, text, or logical
 Data type specifies the kind of data a variable can hold
 Data types help in performing correct operations on data

🔹 Introduction

 In programming, data type is an important concept


 Variables can store different types of data
 In R, variables do not need to be declared with a type
 Data type can change dynamically in R

🔹 Dynamic Nature of R

Theory Points:

 R allows variables to change data type


 No need to declare type before assigning
 Same variable can store different types at different times

🔹 Example Program

my_var <- 30
my_var <- "Sally"

print(my_var)
Explanation:

 First, variable stores numeric value


 Then it changes to character
 Shows dynamic typing in R

🔹 Basic Data Types in R


🔸 1. Numeric

Theory Points:

 Stores decimal or real numbers


 Used for calculations
 Default type for numbers

Example Program
x <- 10.5
class(x)

🔸 2. Integer

Theory Points:

 Stores whole numbers


 Declared using L suffix
 Used when exact integer value needed

Example Program
x <- 100L
class(x)

🔸 3. Complex

Theory Points:

 Stores numbers with real and imaginary part


 Imaginary part is represented using i
 Used in advanced mathematical calculations

Example Program
x <- 3 + 2i
class(x)

🔸 4. Character (String)

Theory Points:

 Stores text or string values


 Written inside quotes
 Used for names, messages, etc.
Example Program
x <- "R is exciting"
class(x)

🔸 5. Logical (Boolean)

Theory Points:

 Stores TRUE or FALSE values


 Used in conditions and decision making
 Important for logical operations

Example Program
x <- TRUE
class(x)

🔹 class() Function
Theory Points:

 Used to identify the data type of a variable


 Helps in checking correctness of data
 Returns the type of variable

🔹 Example Program

x <- 10.5
class(x)

y <- "Hello"
class(y)

🔹 Uses

 Helps to store different types of data


 Used in data analysis and processing
 Helps to avoid errors in programs
 Useful for correct operations
 Used in real-world applications

🔹 Real-Time Example
 Marks → Numeric
 Age → Integer
 Name → Character
 Result → Logical

🔹 Conclusion

 Data types are important for storing and handling data correctly in R
programming
7, Explain Data Structures in R

🔹 Definition (Write ANY 3–4)

 Data structures are used to store and organize data in R


 They help to manage and process data efficiently
 They define how data is arranged and accessed
 Used to handle different types of data

🔹 Introduction

 R provides many built-in data structures


 Each structure is used for different purposes
 Helps in data analysis and processing
 Important structures are vector, list, matrix, array, data frame

🔹 Types of Data Structures in R

🔸 1. Vectors

Theory Points:

 Basic data structure


 Stores same type values
 Used for simple data

🔹 Example Program

fruits <- c("banana", "apple", "orange")

fruits
🔹 Output
[1] "banana" "apple" "orange"

🔸 2. Lists
Theory Points:

 Stores different types of data


 Can combine values
 Flexible structure

🔹 Example Program

thislist <- list("apple", "banana", 50, 100)

thislist
🔹 Output
[[1]]
[1] "apple"

[[2]]
[1] "banana"

[[3]]
[1] 50

[[4]]
[1] 100

🔸 3. Matrices

Theory Points:

 2D structure
 Same type elements
 Rows and columns

🔹 Example Program

thismatrix <- matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2)

thismatrix
🔹 Output
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
🔸 4. Arrays

Theory Points:

 Multi-dimensional
 Same type values
 Used for complex data

🔹 Example Program 1

thisarray <- c(1:24)

thisarray
🔹 Output
[1] 1 2 3 ... 24

🔸 5. Data Frames

Theory Points:

 Table format
 Different data types
 Used in real data

🔹 Example Program

Data_Frame <- [Link](


Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)

Data_Frame
🔹 Output
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
🔹 Summary Table
Data Structure Contains Same Type? Use Case
Vector List of values Yes Simple data
List Mixed values No Group data
Matrix 2D data Yes Table
Array Multi-dimension Yes Complex data
Data Frame Table data No Real-world data

🔹 Uses

 Store and organize data


 Perform data analysis
 Handle large datasets
 Improve program efficiency
 Used in real-world applications

🔹 Conclusion

 Data structures help in efficient data storage and processing in R


8, Explain Functions in R

🔹 Definition (Write ANY 3–4)

 A function is a block of code that runs only when it is called


 A function is used to perform a specific task
 Functions can take input and return output
 Functions help in reducing code repetition

🔹 Introduction

 Functions are used to divide program into smaller parts


 Helps to reuse code multiple times
 Improves readability and efficiency
 R supports user-defined functions

🔹 Creating a Function
Theory Points:

 Created using function() keyword


 Stored in a variable name
 Code is written inside {}

🔹 Example Program

my_function <- function() {


print("Hello World!")
}
🔹 Output

(No output until function is called)

🔹 Calling a Function
Theory Points:

 Function is called using its name with ()


 Executes the code inside function
 Can be called multiple times
🔹 Example Program

my_function <- function() {


print("Hello World!")
}

my_function()
🔹 Output
[1] "Hello World!"

🔹 Arguments (Parameters)
Theory Points:

 Arguments are values passed into function


 Defined inside parentheses
 Multiple arguments separated by comma

🔹 Example Program

my_function <- function(name) {


paste("Hello", name)
}

my_function("Bab")
🔹 Output
[1] "Hello Bab"

🔹 Number of Arguments
Theory Points:

 Function must receive correct number of arguments


 Missing arguments cause error
 Extra arguments also cause error

🔹 Example Program

my_function <- function(a, b) {


a+b
}
my_function(5, 3)
🔹 Output
[1] 8

🔹 Default Parameter Value


Theory Points:

 Default value is used if no argument is passed


 Makes function flexible
 Avoids errors

🔹 Example Program

my_function <- function(country = "India") {


paste("I am from", country)
}

my_function()
🔹 Output
[1] "I am from India"

🔹 Return Values
Theory Points:

 return() is used to send result back


 Function can return value
 Used in calculations

🔹 Example Program

my_function <- function(x) {


return(2 * x)
}

print(my_function(5))
🔹 Output
[1] 10
🔹 Uses

 Reduces code repetition


 Improves readability
 Performs calculations
 Helps in modular programming
 Used in real-world applications

🔹 Real-Time Example

 Function to calculate total marks


 Function to greet user
 Function to calculate salary

🔹 Conclusion

 Functions are important for writing efficient and reusable programs in R

Explain Nested Functions in R

🔹 Definition (Write ANY 3–4)

 A nested function is a function inside another function


 It is used when one function depends on another function
 Nested functions help in modular programming
 It allows code reuse and better organization

🔹 Introduction

 In R, a function can be used inside another function


 It helps to break complex problems into smaller parts
 Improves code readability
 There are two ways to use nested functions
🔹 Types of Nested Functions

🔸 1. Calling a Function inside Another Function

Theory Points:

 One function is used as input to another function


 Inner function executes first
 Result is passed to outer function

🔹 Example Program

Nested_function <- function(x, y) {


a <- x + y
return(a)
}

Nested_function(Nested_function(2,2), Nested_function(3,3))

🔹 Output

[1] 10
Explanation:

 Nested_function(2,2) → 4
 Nested_function(3,3) → 6
 Final → 4 + 6 = 10

🔸 2. Function Inside a Function

Theory Points:

 A function is defined inside another function


 Inner function cannot be called directly
 Outer function must be called first

🔹 Example Program

Outer_func <- function(x) {


Inner_func <- function(y) {
a <- x + y
return(a)
}
return(Inner_func)
}

output <- Outer_func(3)


output(5)

🔹 Output

[1] 8
Explanation:

 Outer_func(3) stores value 3


 Inner_func adds 3 + 5
 Result = 8

🔹 Uses

 Helps in breaking complex problems


 Improves code organization
 Supports code reuse
 Makes program modular
 Used in real-world applications

🔹 Real-Time Example

 Function inside function for calculating total + average


 Used in data processing steps
 Used in multi-step calculations

🔹 Conclusion

 Nested functions help to organize code and solve complex problems easily

Explain Recursion in R
🔹 Definition (Write ANY 3–4)

 Recursion is a process where a function calls itself


 It is used to repeat a task until a condition is met
 Recursion helps to solve problems step by step
 It is a looping technique using functions

🔹 Introduction

 In R, a function can call itself repeatedly


 Each call works with smaller values
 Recursion stops when a base condition is reached
 It is useful for solving mathematical problems

🔹 Working of Recursion
Theory Points:

 Function calls itself


 A condition is checked (if)
 Value decreases each time
 Stops when condition becomes false

🔹 Example Program

tri_recursion <- function(k) {


if (k > 0) {
result <- k + tri_recursion(k - 1)
print(result)
} else {
result <- 0
return(result)
}
}

tri_recursion(3)

🔹 Output

[1] 1
[1] 3
[1] 6
🔹 Explanation

 tri_recursion(3) → 3 + tri_recursion(2)
 tri_recursion(2) → 2 + tri_recursion(1)
 tri_recursion(1) → 1 + tri_recursion(0)
 tri_recursion(0) → stops

Final outputs printed step by step

🔹 Advantages / Uses

 Used to solve complex problems easily


 Useful in mathematical calculations
 Reduces code length
 Used in tree and data structures
 Makes logic simple

🔹 Disadvantages

 Can be slow
 Uses more memory
 May cause infinite loop if condition is wrong

🔹 Real-Time Example

 Factorial calculation
 Sum of numbers
 Fibonacci series

🔹 Conclusion

 Recursion is a powerful technique where a function calls itself to solve problems step
by step

Explain Global Variables in R


🔹 Definition (Write ANY 3–4)

 Global variables are variables created outside a function


 They can be accessed anywhere in the program
 Global variables are available inside and outside functions
 They store values that are used by multiple functions

🔹 Introduction

 Variables in R can be global or local


 Global variables are created outside functions
 They can be used inside functions also
 Helps in sharing data across program

🔹 Global Variables
Theory Points:

 Declared outside any function


 Accessible everywhere
 Same value used throughout program
 Useful for common data

🔹 Example Program

txt <- "awesome"

my_function <- function() {


paste("R is", txt)
}

my_function()

🔹 Output

[1] "R is awesome"


🔹 Local Variables
Theory Points:

 Declared inside a function


 Accessible only inside that function
 Cannot be used outside
 Temporary in nature

🔹 Example Program

txt <- "global variable"

my_function <- function() {


txt <- "fantastic"
paste("R is", txt)
}

my_function()

txt

🔹 Output

[1] "R is fantastic"


[1] "global variable"

🔹 Global Assignment Operator (<<-)


Theory Points:

 Used to create global variable inside function


 Changes global variable value
 Works outside function also
 Denoted by <<-

🔹 Example Program

txt <- "awesome"

my_function <- function() {


txt <<- "fantastic"
}
my_function()

print(txt)

🔹 Output

[1] "fantastic"

🔹 Uses

 Used to share data between functions


 Helps in maintaining common values
 Used in large programs
 Improves data accessibility
 Used in real-world applications

🔹 Real-Time Example

 Global variable for company name


 Used in multiple functions
 Shared data in application

🔹 Conclusion

 Global variables are useful for accessing and modifying data across functions in R
9, Explain Factors in R

🔹 Definition (Write ANY 3–4)

 A factor is a data structure used to store categorical data


 It represents data with fixed categories or levels
 Factors are used to group similar values
 It stores data as levels and labels

🔹 Introduction

 Factors are used to handle categorical data in R


 They store values as levels (categories)
 Commonly used in data analysis
 Example: Gender, Grade, Status

🔹 Creating Factors
Theory Points:

 Created using factor() function


 Converts data into categories
 Stores unique values as levels

🔹 Example Program

gender <- factor(c("Male", "Female", "Male", "Female"))

gender

🔹 Output

[1] Male Female Male Female


Levels: Female Male

Explanation:

 Data is converted into categories


 Unique values become levels
🔹 Levels in Factors
Theory Points:

 Levels are unique categories in factor


 Can be viewed using levels()
 Helps in organizing data

🔹 Example Program

gender <- factor(c("Male", "Female", "Male"))

levels(gender)

🔹 Output

[1] "Female" "Male"

🔹 Advantages / Uses

 Used to store categorical data


 Helps in data analysis
 Reduces memory usage
 Organizes data properly
 Used in statistical models

🔹 Real-Time Example

 Gender → Male/Female
 Grade → A, B, C
 Status → Pass/Fail

🔹 Conclusion

 Factors are useful for handling and analyzing categorical data in R


10, Explain Sorting of Numeric, Character and Factor Vectors in R

🔹 Definition (Write ANY 3–4)

 Sorting is the process of arranging data in a specific order


 It can be ascending or descending order
 Sorting is used to organize data for analysis
 In R, sorting is done using sort() function

🔹 Introduction

 Sorting helps to arrange data properly


 It is used in data analysis and reporting
 R supports sorting for numeric, character, and factor data
 It improves data understanding

🔹 Sorting Numeric Vectors


Theory Points:

 Numeric values are sorted in ascending order by default


 Can be sorted in descending using decreasing = TRUE
 Used for numbers

🔹 Example Program

nums <- c(5, 2, 9, 1)

sort(nums)
🔹 Output
[1] 1 2 5 9

🔹 Descending Order

sort(nums, decreasing = TRUE)


🔹 Output
[1] 9 5 2 1
🔹 Sorting Character Vectors
Theory Points:

 Sorted in alphabetical order


 Based on ASCII values
 Case-sensitive

🔹 Example Program

names <- c("Banana", "Apple", "Orange")

sort(names)
🔹 Output
[1] "Apple" "Banana" "Orange"

🔹 Sorting Factor Vectors


Theory Points:

 Factors are sorted based on levels


 Used for categorical data
 Order depends on factor levels

🔹 Example Program

f <- factor(c("High", "Low", "Medium"))

sort(f)
🔹 Output
[1] High Low Medium
Levels: High Low Medium

🔹 Uses

 Helps to arrange data clearly


 Used in data analysis
 Makes data easy to understand
 Used in reports and graphs
 Improves data processing
🔹 Real-Time Example

 Sorting marks → highest to lowest


 Sorting names → alphabetical order
 Sorting grades → A, B, C

🔹 Conclusion

 Sorting is an important operation used to organize and analyze data effectively in R


11, Explain Special Values in R

🔹 Definition (Write ANY 3–4)

 Special values are reserved constants used to handle missing, undefined, or infinite
data in R
 They are used to represent exceptional conditions in data
 Special values help in data cleaning and analysis
 They represent non-standard values like NA, NaN, Inf, and NULL

🔹 Introduction

 In real-world data, some values may be missing or undefined


 R provides special values to handle such situations
 These include NA, NaN, Inf, and NULL
 They are important for data analysis and error handling

🔹 Types of Special Values

🔸 1. NA (Not Available)

Theory Points:

 Represents missing or unavailable data


 Logical constant but can be converted to other types
 Detected using [Link]() function

🔹 Example Program

x <- c(10, NA, 20)

[Link](x)
🔹 Output
[1] FALSE TRUE FALSE

🔸 2. NaN (Not a Number)


Theory Points:

 Represents undefined mathematical results


 Example: 0/0 or invalid operations
 Checked using [Link]()

🔹 Example Program

x <- 0/0

x
[Link](x)
🔹 Output
[1] NaN
[1] TRUE

🔸 3. Inf and -Inf (Infinity)

Theory Points:

 Represents infinite values


 Occurs when dividing by zero
 Checked using [Link]()

🔹 Example Program

x <- 1/0

x
[Link](x)
🔹 Output
[1] Inf
[1] TRUE

🔸 4. NULL

Theory Points:

 Represents empty or no value


 Has length zero
 Checked using [Link]()
🔹 Example Program

x <- NULL

x
[Link](x)
🔹 Output
NULL
[1] TRUE

🔹 Summary Table
Value Meaning Function Cause
NA Missing data [Link]() Incomplete data
NaN Not a number [Link]() 0/0, invalid math
Inf Infinity [Link]() Division by zero
NULL Empty value [Link]() No data

🔹 Uses

 Used to handle missing data


 Helps in error handling
 Used in data cleaning
 Important in data analysis
 Used in real-world datasets

🔹 Real-Time Example

 Missing marks → NA
 Invalid calculation → NaN
 Divide by zero → Inf
 Empty data → NULL

🔹 Conclusion

 Special values are essential for handling missing, undefined, and infinite data in R
programming
11, Explain Creating Variables, Numeric, Character, Logical Data, Vectors and Data
Frames in R

🔹 Definition (Write ANY 3–4)

 Variables are containers used to store data values


 Data types define the type of data stored
 Vectors and data frames are data structures used to organize data
 These concepts help in data storage and analysis in R

🔹 Introduction

 R is used to store and process data


 Variables are used to store values
 Data types define kind of data
 Vectors and data frames help to organize data efficiently

🔹 Creating Variables
Theory Points:

 Variables are created using <- or =


 No need to declare variable type
 Value is assigned directly

🔹 Example Program

name <- "John"


age <- 25

name
age
🔹 Output
[1] "John"
[1] 25
🔹 Numeric Data
Theory Points:

 Stores numbers (integer or decimal)


 Used for mathematical operations
 Default numeric type in R

🔹 Example Program

x <- 10.5

x
🔹 Output
[1] 10.5

🔹 Character Data
Theory Points:

 Stores text or string values


 Written inside quotes
 Used for names, messages

🔹 Example Program

name <- "Bab"

name
🔹 Output
[1] "Bab"

🔹 Logical Data
Theory Points:

 Stores TRUE or FALSE values


 Used in conditions
 Helps in decision making

🔹 Example Program
flag <- TRUE

flag
🔹 Output
[1] TRUE

🔹 Vectors
Theory Points:

 Collection of same type values


 Created using c() function
 Basic data structure in R

🔹 Example Program

marks <- c(80, 90, 85)

marks
🔹 Output
[1] 80 90 85

🔹 Data Frames
Theory Points:

 Table-like structure
 Can store different types of data
 Organized in rows and columns

🔹 Example Program

df <- [Link](
name = c("A", "B"),
marks = c(80, 90)
)

df
🔹 Output
name marks
1 A 80
2 B 90
🔹 Uses

 Used to store and manage data


 Helps in data analysis
 Organizes data efficiently
 Used in real-world applications
 Improves program clarity

🔹 Real-Time Example

 Store student name → Character


 Store marks → Numeric
 Store result → Logical
 Store all details → Data Frame

🔹 Conclusion

 Variables, data types, vectors, and data frames are essential for data storage and
processing in R programming
12, Explain Control Structures in R (with Statements)

🔹 Definition (Write ANY 3–4)

 Control structures are used to control the flow of execution of a program


 They help to make decisions in a program
 They determine which statement should be executed
 Used for logical and conditional programming

🔹 Introduction

 Control structures are used for decision making


 They execute code based on conditions
 R provides if, else, else-if statements
 These are called conditional statements

🔹 Types of Control Statements

🔸 1. if Statement
🔹 Definition (ANY 3)

 if statement is used to check a condition


 It executes code only when condition is TRUE
 It is used for simple decision making

🔹 Syntax
if (condition) {
# code
}

🔹 Simple Code
x <- 10

if (x > 5) {
print("Greater")
}
🔹 Output
[1] "Greater"

🔸 2. if-else Statement
🔹 Definition (ANY 3)

 if-else is used to handle two conditions


 Executes one block if TRUE and another if FALSE
 Used for decision making with alternatives

🔹 Syntax
if (condition) {
# code
} else {
# code
}

🔹 Simple Codee
x <- 3

if (x > 5) {
print("Greater")
} else {
print("Smaller")
}

🔹 Output
[1] "Smaller"

🔸 3. else-if Statement
🔹 Definition (ANY 3)

 else-if is used to check multiple conditions


 Executes when previous condition is FALSE
 Used for multiple decision making

🔹 Syntax
if (condition) {
# code
} else if (condition) {
# code
} else {
# code
}

🔹 Simple Code
x <- 5

if (x > 5) {
print("Greater")
} else if (x == 5) {
print("Equal")
} else {
print("Smaller")
}

🔹 Output
[1] "Equal"

🔸 4. Nested if Statement
🔹 Definition (ANY 3)

 Nested if means if inside another if


 Used for multiple level conditions
 Helps in complex decision making

🔹 Syntax
if (condition) {
if (condition) {
# code
}
}

🔹 Simple Code
x <- 20

if (x > 10) {
if (x > 15) {
print("Greater than 15")
}
}
🔹 Output
[1] "Greater than 15"

AND Operator (&)


🔹 Definition (ANY 3)

 AND operator is used to combine two conditions


 It returns TRUE only if both conditions are TRUE
 Represented by & symbol

🔹 Syntax
condition1 & condition2

🔹 Simple Code
a <- 10

if (a > 5 & a < 20) {


print("Both conditions are true")
}

🔹 Output
[1] "Both conditions are true"

🔹 Real-Time Example

👉 Checking age between 18 and 60

🔸 2. OR Operator (|)
🔹 Definition (ANY 3)

 OR operator is used to combine conditions


 It returns TRUE if any one condition is TRUE
 Represented by | symbol

🔹 Syntax
condition1 | condition2
🔹 Simple Code
a <- 10

if (a < 5 | a < 20) {


print("At least one condition is true")
}

🔹 Output
[1] "At least one condition is true"

🔹 Real-Time Example

👉 Student pass if internal OR external marks are enough

Explain Loops in R

🔹 Definition (Write ANY 3–4)

 Loops are used to execute a block of code repeatedly


 They reduce manual work and repetition
 Loops run based on conditions or sequences
 They improve program efficiency

🔹 Introduction

 Loops help in repeating tasks automatically


 Used when same operation needed multiple times
 R provides for, while, and repeat loops
 Useful in data processing

🔹 Types of Loops

🔸 1. for Loop
🔹 Definition (ANY 3)

 for loop is used to iterate over a sequence


 It runs for a fixed number of times
 Used when number of iterations is known

🔹 Syntax
for (variable in sequence) {
# code
}

🔹 Simple Code
for (i in 1:3) {
print(i)
}

🔹 Output
[1] 1
[1] 2
[1] 3

🔹 Real-Time Example

👉 Printing student roll numbers

🔸 2. while Loop
🔹 Definition (ANY 3)

 while loop executes code while condition is TRUE


 Stops when condition becomes FALSE
 Used when number of iterations is unknown

🔹 Syntax
while (condition) {
# code
}

🔹 Simple Code
i <- 1

while (i <= 3) {
print(i)
i <- i + 1
}

🔹 Output
[1] 1
[1] 2
[1] 3

🔹 Real-Time Example

👉 Printing numbers until condition satisfied

🔸 3. repeat Loop
🔹 Definition (ANY 3)

 repeat loop runs continuously


 It stops only when break is used
 Used for infinite loops with condition

🔹 Syntax
repeat {
# code
if (condition) {
break
}
}

🔹 Simple Code
i <- 1

repeat {
print(i)
i <- i + 1

if (i > 3) {
break
}
}
🔹 Output
[1] 1
[1] 2
[1] 3

🔹 Real-Time Example

👉 Menu-driven program until user exits

🔹 Loop Control Statements

🔸 break

🔹 Definition

 break is used to stop the loop immediately


 It exits loop before completion

🔹 Code
for (i in 1:5) {
if (i == 3) {
break
}
print(i)
}

🔹 Output
[1] 1
[1] 2

🔸 next

🔹 Definition

 next is used to skip current iteration


 Loop continues with next value
🔹 Code
for (i in 1:5) {
if (i == 3) {
next
}
print(i)
}

🔹 Output
[1] 1
[1] 2
[1] 4
[1] 5

🔹 Conclusion

 Loops help in repeating tasks efficiently in R


 They reduce manual work and improve logic
13, Explain Scoping Rules in R

🔹 Definition (Write ANY 3–4)

 Scoping rules define how R looks for variable values


 They decide where a variable can be used in a program
 They determine the visibility of variables
 Scoping helps in managing variables inside and outside functions

🔹 Introduction

 In R, variables can be local or global


 Scope means area where variable is accessible
 R follows lexical scoping rules
 It helps to avoid confusion in variable usage

🔹 Types of Scope

🔸 1. Local Scope
🔹 Definition (ANY 3)

 Local variables are created inside a function


 They can be used only inside that function
 They are not accessible outside

🔹 Simple Code
my_function <- function() {
x <- 10
print(x)
}

my_function()

🔹 Output
[1] 10
🔸 2. Global Scope
🔹 Definition (ANY 3)

 Global variables are created outside functions


 They can be used anywhere in the program
 Accessible inside and outside functions

🔹 Simple Code
x <- 20

my_function <- function() {


print(x)
}

my_function()

🔹 Output
[1] 20

🔹 Lexical Scoping (Important)


🔹 Definition (ANY 3)

 R follows lexical scoping


 It searches variables in current and parent environments
 If not found, it searches global environment

🔹 Simple Code
x <- 5

my_function <- function() {


print(x)
}

my_function()

🔹 Output
[1] 5
🔹 Changing Global Variable (<<-)
🔹 Definition (ANY 3)

 <<- is used to modify global variable inside function


 It changes value in global scope
 Used when global value needs update

🔹 Simple Code
x <- 10

my_function <- function() {


x <<- 50
}

my_function()

print(x)

🔹 Output
[1] 50

🔹 Uses

 Helps to manage variables properly


 Avoids variable conflicts
 Improves program clarity
 Used in function programming

🔹 Conclusion

 Scoping rules help to control variable access and visibility in R


14, Explain Dates and Times in R

🔹 Definition (Write ANY 3–4)

 Dates and times are used to represent date and time values in R
 They help in handling time-based data
 Used for data analysis involving time
 R provides built-in functions to manage dates and times

🔹 Introduction

 In real-world data, date and time are very important


 R provides special classes like Date and POSIXct
 Used in data analysis, reports, and applications
 Helps in time calculations and comparisons

🔹 Date in R
🔹 Definition (ANY 3)

 Date represents calendar date (year, month, day)


 Stored using Date class
 Created using [Link]() function

🔹 Syntax
[Link]("YYYY-MM-DD")

🔹 Simple Code
d <- [Link]("2024-01-01")

🔹 Output
[1] "2024-01-01"

🔹 Current Date
🔹 Code
[Link]()
🔹 Output (example)
[1] "2026-04-11"

🔹 Date and Time (POSIXct)


🔹 Definition (ANY 3)

 POSIXct stores date and time together


 Includes year, month, day, hour, minute, second
 Used for accurate time calculations

🔹 Syntax
[Link]("YYYY-MM-DD HH:MM:SS")

🔹 Simple Code
dt <- [Link]("2024-01-01 10:30:00")

dt

🔹 Output
[1] "2024-01-01 10:30:00"

🔹 Current Date and Time


🔹 Code
[Link]()

🔹 Output (example)
[1] "2026-04-11 12:30:00"

🔹 Operations on Date
🔹 Example
d1 <- [Link]("2024-01-01")
d2 <- [Link]("2024-01-10")

d2 - d1

🔹 Output
Time difference of 9 days
🔹 Uses

 Used in time-based data analysis


 Helps in calculating duration
 Used in reports and logs
 Important in real-world applications

🔹 Real-Time Example

 Attendance date
 Transaction time
 Login time

🔹 Conclusion

 Dates and times are important for handling and analyzing time-related data in R
15, Explain Introduction to Functions in R

🔹 Definition (Write ANY 3–4)

 A function is a block of code that performs a specific task


 It runs only when it is called
 Functions help to reuse code and reduce repetition
 Functions can take input and return output

🔹 Introduction

 Functions are used to divide a program into smaller parts


 They improve readability and efficiency
 Functions avoid repeating the same code
 R provides built-in and user-defined functions

🔹 Types of Functions
🔹 1. Built-in Functions

 Already available in R
 Used directly
 Example: sum(), mean()

🔹 Example Code
x <- c(1,2,3)

sum(x)
🔹 Output
[1] 6

🔹 2. User-defined Functions

 Created by user
 Written using function()
 Used for custom tasks
🔹 Example Code
my_function <- function() {
print("Hello")
}

my_function()
🔹 Output
[1] "Hello"

🔹 Components of a Function
🔹 Definition (ANY 3)

 Function name → identifies function


 Parameters → input values
 Function body → code inside function

🔹 Syntax
function_name <- function(parameters) {
# code
}

🔹 Advantages of Functions

 Reduces code repetition


 Improves readability
 Easy to debug
 Saves time
 Helps modular programming

🔹 Real-Time Example

 Function to calculate marks


 Function to display message
 Function to calculate salary

🔹 Conclusion

 Functions are essential for efficient and reusable programming in R


16, Explain Important R Data Structures (Preview)

🔹 Definition (Write ANY 3–4)

 Data structures are used to store and organize data in R


 They help to manage different types of data efficiently
 Data structures define how data is stored and accessed
 They are essential for data analysis and processing

🔹 Introduction

 R provides different data structures to handle data


 Each structure is used for different purposes
 They help in organizing and analyzing data
 Important structures include vectors, matrices, lists, and data frames

🔹 Types of Important Data Structures

🔸 1. Vectors
🔹 Definition (ANY 3)

 A vector is a basic data structure in R


 It contains elements of the same data type
 Created using c() function

🔹 Simple Code
v <- c(1, 2, 3)

v
🔹 Output
[1] 1 2 3

🔸 2. Matrices
🔹 Definition (ANY 3)

 Matrix is a 2D data structure


 Contains elements of the same type
 Arranged in rows and columns

🔹 Simple Code
m <- matrix(c(1,2,3,4), nrow = 2)

m
🔹 Output
[,1] [,2]
[1,] 1 3
[2,] 2 4

🔸 3. Lists
🔹 Definition (ANY 3)

 List can store different types of data


 It is a flexible structure
 Can contain numbers, strings, vectors

🔹 Simple Code
l <- list(1, "A", TRUE)

l
🔹 Output
[[1]]
[1] 1

[[2]]
[1] "A"

[[3]]
[1] TRUE

🔸 4. Data Frames
🔹 Definition (ANY 3)

 Data frame is a table-like structure


 Stores data in rows and columns
 Columns can have different data types
🔹 Simple Code
df <- [Link](name = c("A","B"), marks = c(80,90))

df
🔹 Output
name marks
1 A 80
2 B 90

🔹 Uses

 Used to store and organize data


 Helps in data analysis
 Supports different types of data handling
 Used in real-world applications

🔹 Conclusion

 Data structures are essential for efficient data storage and processing in R
17, Explain Vectors in R

🔹 Definition (Write ANY 3–4)

 A vector is a basic data structure in R


 It contains elements of the same data type
 It is used to store multiple values in one variable
 Vectors are created using c() function

🔹 Introduction

 Vectors are the foundation of R programming


 Used to store multiple values efficiently
 All elements must be of same type
 Widely used in data analysis

🔹 Creating Vectors
🔹 Definition (ANY 3)

 Creating vectors means storing multiple values in one variable


 Vectors are created using c() function
 All elements must be of same data type

🔹 Code
fruits <- c("banana", "apple", "orange")
fruits
🔹 Output
[1] "banana" "apple" "orange"

🔹 Sequence Vectors
🔹 Definition (ANY 3)

 Sequence vectors generate ordered values


 Created using : or seq()
 Used for numeric sequences
🔹 Code
numbers <- 1:5
numbers
🔹 Output
[1] 1 2 3 4 5

🔹 Generating Sequences (seq)


🔹 Definition (ANY 3)

 seq() is used to generate sequence with step values


 Allows control over start, end, and interval
 Used for flexible sequences

🔹 Code
numbers <- seq(0, 10, by = 2)
numbers
🔹 Output
[1] 0 2 4 6 8 10

🔹 Length of Vector
🔹 Definition (ANY 3)

 Length is the number of elements in vector


 Found using length()
 Used to measure vector size

🔹 Code
length(fruits)
🔹 Output
[1] 3

🔹 Sorting Vector
🔹 Definition (ANY 3)

 Sorting means arranging elements in order


 Done using sort()
 Can be ascending or descending
🔹 Code
sort(c(5,2,9))
🔹 Output
[1] 2 5 9

🔹 Accessing Elements
🔹 Definition (ANY 3)

 Accessing means retrieving values using index


 Index starts from 1 in R
 Can access single or multiple elements

🔹 Code
fruits[1]
🔹 Output
[1] "banana"

🔹 Multiple Access
fruits[c(1,3)]
🔹 Output
[1] "banana" "orange"

🔹 Negative Index
fruits[-1]
🔹 Output
[1] "apple" "orange"

🔹 Modifying Elements
🔹 Definition (ANY 3)

 Modifying means changing vector values


 Done using index assignment
 Used to update data

🔹 Code
fruits[1] <- "pear"
fruits
🔹 Output
[1] "pear" "apple" "orange"

🔹 Repeating Vectors
🔹 Definition (ANY 3)

 Repeating vectors means duplicating elements


 Done using rep()
 Used to create repeated patterns

🔹 Code
rep(c(1,2,3), times = 2)
🔹 Output
[1] 1 2 3 1 2 3

🔹 Uses

 Store multiple values


 Perform operations
 Used in data analysis
 Easy data handling
 Used in real-world applications

🔹 Conclusion

 Vectors are the most important data structure in R for storing and processing
data
18, Explain Lists in R

🔹 Definition (Write ANY 3–4)

 A list is a data structure that can store different types of data


 It is an ordered and changeable collection
 Lists can contain numbers, strings, vectors, or other lists
 Lists are created using list() function

🔹 Introduction

 Lists are used when data types are different


 Unlike vectors, lists can store mixed data types
 They are flexible and widely used in R
 Useful in data handling and analysis

🔹 Creating a List
🔹 Definition (ANY 3)

 Lists are created using list() function


 Can store multiple types of data
 Elements are stored in order

🔹 Code
thislist <- list("apple", "banana", "cherry")

thislist
🔹 Output
[[1]]
[1] "apple"

[[2]]
[1] "banana"

[[3]]
[1] "cherry"
🔹 Accessing List Elements
🔹 Definition (ANY 3)

 Elements are accessed using index number


 Index starts from 1
 Can access one or more elements

🔹 Code
thislist[1]
🔹 Output
[[1]]
[1] "apple"

🔹 Modifying List Elements


🔹 Definition (ANY 3)

 Elements can be changed using index


 Lists are mutable (changeable)
 Used to update values

🔹 Code
thislist[1] <- "blackcurrant"

thislist
🔹 Output
[[1]]
[1] "blackcurrant"

[[2]]
[1] "banana"

[[3]]
[1] "cherry"

🔹 Length of List
🔹 Definition (ANY 3)

 Length means number of elements in list


 Found using length()
 Helps to measure list size
🔹 Code
length(thislist)
🔹 Output
[1] 3

🔹 Check Item Exists


🔹 Definition (ANY 3)

 %in% is used to check element presence


 Returns TRUE or FALSE
 Used for searching

🔹 Code
"apple" %in% thislist
🔹 Output
[1] TRUE

🔹 Adding Elements
🔹 Definition (ANY 3)

 Elements can be added using append()


 Can add at end or specific position
 Used to expand list

🔹 Code
append(thislist, "orange")
🔹 Output
[[1]] "blackcurrant"
[[2]] "banana"
[[3]] "cherry"
[[4]] "orange"

🔹 Removing Elements
🔹 Definition (ANY 3)

 Elements can be removed using negative index


 Creates updated list
 Used to delete unwanted values
🔹 Code
newlist <- thislist[-1]

newlist
🔹 Output
[[1]]
[1] "banana"

[[2]]
[1] "cherry"

🔹 Range of Index
🔹 Definition (ANY 3)

 Range selects multiple elements


 Uses : operator
 Helps in slicing list

🔹 Code
thislist <- list("a","b","c","d","e")

thislist[2:4]
🔹 Output
[[1]] "b"
[[2]] "c"
[[3]] "d"

🔹 Loop Through List


🔹 Definition (ANY 3)

 Lists can be iterated using loop


 for loop is commonly used
 Used to access all elements

🔹 Code
for (x in thislist) {
print(x)
}
🔹 Output
[1] "blackcurrant"
[1] "banana"
[1] "cherry"

🔹 Joining Lists
🔹 Definition (ANY 3)

 Lists can be combined using c()


 Used to merge multiple lists
 Creates a new list

🔹 Code
list1 <- list("a","b")
list2 <- list(1,2)

list3 <- c(list1, list2)

list3

🔹 Output
[[1]] "a"
[[2]] "b"
[[3]] 1
[[4]] 2

🔹 Uses

 Store mixed data


 Flexible data structure
 Used in complex data handling
 Used in real-world applications

🔹 Conclusion

 Lists are important data structures used to store and manage different types of data
in R
19, Explain Matrices in R

🔹 Definition (Write ANY 3–4)

 A matrix is a two-dimensional data structure in R


 It contains elements arranged in rows and columns
 All elements must be of the same data type
 Matrix is created using matrix() function

🔹 Introduction

 Matrix is used to store tabular data


 It has rows (horizontal) and columns (vertical)
 Useful for mathematical operations
 Widely used in data analysis

🔹 Creating Matrix
🔹 Definition (ANY 3)

 Matrix is created using matrix()


 Requires nrow and ncol
 Elements are combined using c()

🔹 Code
thismatrix <- matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2)

thismatrix
🔹 Output
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6

🔹 Accessing Elements
🔹 Definition (ANY 3)

 Elements accessed using row and column index


 Syntax: [row, column]
 Index starts from 1

🔹 Code
thismatrix[1,2]
🔹 Output
[1] 4

🔹 Accessing Rows & Columns


🔹 Definition (ANY 3)

 Whole row or column can be accessed


 Use comma to specify
 Helps in extracting data

🔹 Code (Row)
thismatrix[2,]
🔹 Output
[1] 2 5

🔹 Code (Column)
thismatrix[,2]
🔹 Output
[1] 4 5 6

🔹 Access Multiple Rows/Columns


🔹 Definition (ANY 3)

 Multiple rows/columns accessed using c()


 Helps in selecting group of values
 Used in data analysis

🔹 Code
thismatrix[c(1,2),]

🔹 Output
[,1] [,2]
[1,] 1 4
[2,] 2 5
🔹 Adding Rows & Columns
🔹 Definition (ANY 3)

 Rows added using rbind()


 Columns added using cbind()
 Used to expand matrix

🔹 Code
newmatrix <- cbind(thismatrix, c(7,8,9))

newmatrix

🔹 Output
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

🔹 Removing Rows & Columns


🔹 Definition (ANY 3)

 Elements removed using negative index


 Creates updated matrix
 Used to delete data

🔹 Code
thismatrix <- thismatrix[-1, -1]

thismatrix

🔹 Output
[,1]
[1,] 5
[2,] 6
🔹 Check Item Exists
🔹 Definition (ANY 3)

 %in% checks if value exists


 Returns TRUE or FALSE
 Used for searching

🔹 Code
4 %in% thismatrix

🔹 Output
[1] FALSE

🔹 Dimension of Matrix
🔹 Definition (ANY 3)

 dim() returns rows and columns


 Shows size of matrix
 Useful for structure analysis

🔹 Code
dim(thismatrix)

🔹 Output
[1] 2 1

🔹 Length of Matrix
🔹 Definition (ANY 3)

 length() gives total elements


 Calculated as rows × columns
 Used to find size

🔹 Code
length(thismatrix)

🔹 Output
[1] 2
🔹 Loop Through Matrix
🔹 Definition (ANY 3)

 Matrix elements accessed using loops


 Used for iteration
 Useful in processing data

🔹 Code
for (i in 1:nrow(thismatrix)) {
for (j in 1:ncol(thismatrix)) {
print(thismatrix[i,j])
}
}

🔹 Combine Matrices
🔹 Definition (ANY 3)

 Matrices combined using rbind() and cbind()


 Used to merge matrices
 Creates new matrix

🔹 Code
m1 <- matrix(c(1,2,3,4), nrow=2)
m2 <- matrix(c(5,6,7,8), nrow=2)

cbind(m1,m2)

🔹 Output
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8

🔹 Uses

 Store tabular data


 Used in calculations
 Used in data analysis
 Easy data representation
 Used in real-world applications
🔹 Conclusion

 Matrices are important data structures used for handling two-dimensional data in R
20, Explain Arrays in R

🔹 Definition (Write ANY 3–4)

 An array is a multi-dimensional data structure in R


 It can store data in more than two dimensions
 All elements in an array must be of the same data type
 Arrays are created using the array() function

🔹 Introduction

 Arrays are an extension of matrices


 Used to store data in multiple dimensions
 Helpful in complex data representation
 Widely used in data analysis and computations

🔹 Creating Array
🔹 Definition (ANY 3)

 Arrays are created using array()


 dim parameter defines dimensions
 Data is provided using c()

🔹 Code
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4,3,2))

multiarray

🔹 Output (sample)
,,1

[,1] [,2] [,3]


[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12

,,2
[,1] [,2] [,3]
[1,] 13 17 21
[2,] 14 18 22
[3,] 15 19 23
[4,] 16 20 24

🔹 Accessing Elements
🔹 Definition (ANY 3)

 Elements accessed using index position


 Syntax: [row, column, matrix]
 Index starts from 1

🔹 Code
multiarray[2,3,2]

🔹 Output
[1] 22

🔹 Access Row / Column


🔹 Definition (ANY 3)

 Can access full row or column


 Uses comma (,) in indexing
 Useful for extracting data

🔹 Code (Row)
multiarray[c(1), ,1]

🔹 Output
[1] 1 5 9

🔹 Code (Column)
multiarray[,c(1),1]

🔹 Output
[1] 1 2 3 4
🔹 Check Item Exists
🔹 Definition (ANY 3)

 %in% checks if value exists


 Returns TRUE or FALSE
 Used for searching

🔹 Code
2 %in% multiarray

🔹 Output
[1] TRUE

🔹 Dimension of Array
🔹 Definition (ANY 3)

 dim() returns dimensions


 Shows rows, columns, layers
 Used to understand structure

🔹 Code
dim(multiarray)

🔹 Output
[1] 4 3 2

🔹 Length of Array
🔹 Definition (ANY 3)

 length() gives total elements


 Used to find size
 Includes all dimensions

🔹 Code
length(multiarray)

🔹 Output
[1] 24
🔹 Loop Through Array
🔹 Definition (ANY 3)

 Arrays can be accessed using loops


 Used to process elements
 Helps in iteration

🔹 Code
for (x in multiarray) {
print(x)
}

🔹 Uses

 Store multi-dimensional data


 Used in scientific calculations
 Helps in complex data handling
 Used in real-world applications
 Supports data analysis

🔹 Conclusion

 Arrays are useful for handling multi-dimensional data efficiently in R


21, Explain Data Frames in R

🔹 Definition (Write ANY 3–4)

 A data frame is a table-like data structure in R


 It stores data in rows and columns
 Each column can have different data types
 Data frames are created using [Link]() function

🔹 Introduction

 Data frames are used to store tabular data


 Similar to Excel tables
 Columns contain same type of data
 Widely used in data analysis

🔹 Creating Data Frame


🔹 Definition (ANY 3)

 Created using [Link]()


 Each column is a vector
 Columns can have different data types

🔹 Code
Data_Frame <- [Link](
Training = c("Strength","Stamina","Other"),
Pulse = c(100,150,120),
Duration = c(60,30,45)
)

Data_Frame

🔹 Output
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
🔹 Summary of Data
🔹 Definition (ANY 3)

 summary() gives statistical summary


 Shows min, max, mean values
 Used for data analysis

🔹 Code
summary(Data_Frame)

🔹 Output (sample)
Training Pulse Duration
Length:3 Min. :100 Min. :30
Class :char Mean :123 Mean :45
Mode :char Max. :150 Max. :60

🔹 Accessing Elements
🔹 Definition (ANY 3)

 Columns accessed using [ ], [[ ]], or $


 Used to retrieve data
 Helps in data manipulation

🔹 Code
Data_Frame$Training

🔹 Output
[1] "Strength" "Stamina" "Other"

🔹 Adding Rows
🔹 Definition (ANY 3)

 Rows added using rbind()


 Used to insert new data
 Must match column structure
🔹 Code
New_row <- rbind(Data_Frame, c("Strength",110,50))

New_row

🔹 Output
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
4 Strength 110 50

🔹 Adding Columns
🔹 Definition (ANY 3)

 Columns added using cbind()


 Used to extend data frame
 Must have same number of rows

🔹 Code
New_col <- cbind(Data_Frame, Steps = c(1000,2000,3000))

New_col

🔹 Output
Training Pulse Duration Steps
1 Strength 100 60 1000
2 Stamina 150 30 2000
3 Other 120 45 3000

🔹 Removing Rows & Columns


🔹 Definition (ANY 3)

 Removed using negative indexing


 Creates updated data frame
 Used to delete unwanted data
🔹 Code
Data_Frame_New <- Data_Frame[-1, -1]

Data_Frame_New

🔹 Output
Pulse Duration
2 150 30
3 120 45

🔹 Dimension of Data Frame


🔹 Definition (ANY 3)

 dim() gives rows and columns


 nrow() gives number of rows
 ncol() gives number of columns

🔹 Code
dim(Data_Frame)
nrow(Data_Frame)
ncol(Data_Frame)

🔹 Output
[1] 3 3
[1] 3
[1] 3

🔹 Length of Data Frame


🔹 Definition (ANY 3)

 length() returns number of columns


 Same as ncol()
 Used to find size

🔹 Code
length(Data_Frame)

🔹 Output
[1] 3
🔹 Combining Data Frames
🔹 Definition (ANY 3)

 Data frames combined using rbind() and cbind()


 Used to merge data
 Creates new data frame

🔹 Code
DF1 <- [Link](A=c(1,2))
DF2 <- [Link](A=c(3,4))

rbind(DF1,DF2)

🔹 Output
A
11
22
33
44

🔹 Uses

 Store tabular data


 Used in data analysis
 Easy data manipulation
 Used in real-world applications
 Similar to Excel

🔹 Conclusion

 Data frames are powerful structures used to store and manage tabular data in R
22, Explain Factors in R

🔹 Definition (Write ANY 3–4)

 Factors are used to categorize data in R


 They store categorical (grouped) values
 Factors contain levels (unique categories)
 Created using factor() function

🔹 Introduction

 Factors are used for categorical data analysis


 Examples: gender, music type, training type
 They help in data grouping and classification
 Widely used in statistical analysis

🔹 Creating Factors
🔹 Definition (ANY 3)

 Factors are created using factor()


 Input is a vector
 Unique values become levels

🔹 Code
music_genre <- factor(c("Jazz","Rock","Classic","Pop"))

music_genre

🔹 Output
[1] Jazz Rock Classic Pop
Levels: Classic Jazz Pop Rock

🔹 Levels of Factor
🔹 Definition (ANY 3)

 Levels are unique categories in factor


 Obtained using levels()
 Used to understand data categories
🔹 Code
levels(music_genre)

🔹 Output
[1] "Classic" "Jazz" "Pop" "Rock"

🔹 Setting Levels
🔹 Definition (ANY 3)

 Levels can be manually defined


 Done using levels argument
 Helps to control categories

🔹 Code
music_genre <- factor(
c("Jazz","Rock","Classic"),
levels = c("Classic","Jazz","Rock","Pop")
)

levels(music_genre)

🔹 Output
[1] "Classic" "Jazz" "Rock" "Pop"

🔹 Length of Factor
🔹 Definition (ANY 3)

 Length means number of elements


 Found using length()
 Includes all values

🔹 Code
length(music_genre)

🔹 Output
[1] 3
🔹 Accessing Elements
🔹 Definition (ANY 3)

 Elements accessed using index


 Index starts from 1
 Used to retrieve values

🔹 Code
music_genre[1]

🔹 Output
[1] Jazz
Levels: Classic Jazz Rock Pop

🔹 Modifying Elements
🔹 Definition (ANY 3)

 Values can be changed using index


 New value must exist in levels
 Otherwise error occurs

🔹 Code
music_genre[1] <- "Rock"

music_genre

🔹 Output
[1] Rock Rock Classic
Levels: Classic Jazz Rock Pop

🔹 Invalid Level Example


🔹 Definition (ANY 3)

 Cannot assign value not in levels


 Produces warning
 Returns NA

🔹 Code
music_genre[1] <- "Opera"
🔹 Output
Warning message:
invalid factor level, NA generated

🔹 Adding New Level


🔹 Definition (ANY 3)

 New levels added using levels argument


 Allows new category values
 Helps in extending data

🔹 Code
music_genre <- factor(
c("Jazz","Rock","Classic"),
levels = c("Classic","Jazz","Rock","Opera")
)

music_genre[1] <- "Opera"

music_genre

🔹 Output
[1] Opera Rock Classic
Levels: Classic Jazz Rock Opera

🔹 Uses

 Used for categorical data


 Helps in classification
 Used in statistical analysis
 Organizes data
 Used in real-world applications

🔹 Conclusion

 Factors are important for handling categorical data efficiently in R


23, Explain Character Strings in R

🔹 Definition (Write ANY 3–4)

 Character strings are used to store text data in R


 They are written inside quotes (" ") or (' ')
 Each element in a string is called a character
 Strings are also called character data type

🔹 Introduction

 Strings are used to store names, messages, text


 They are widely used in data processing
 R provides functions to manipulate strings
 Strings are important in real-world applications

🔹 Creating Strings
🔹 Definition (ANY 3)

 Strings are created using quotes


 Can store single or multiple characters
 Stored as character type

🔹 Code
name <- "Bab"

name

🔹 Output
[1] "Bab"

🔹 Multiple Strings (Vector)


🔹 Definition (ANY 3)

 Multiple strings stored using vector


 Created using c()
 Used to store list of text
🔹 Code
fruits <- c("apple", "banana", "mango")

fruits

🔹 Output
[1] "apple" "banana" "mango"

🔹 String Length
🔹 Definition (ANY 3)

 nchar() is used to find length of string


 Counts number of characters
 Used in text analysis

🔹 Code
nchar("Bab")

🔹 Output
[1] 3

🔹 Combining Strings
🔹 Definition (ANY 3)

 Strings can be combined using paste()


 Used to join text
 Helps in formatting output

🔹 Code
paste("Hello", "Bab")

🔹 Output
[1] "Hello Bab"
🔹 Changing Case
🔹 Definition (ANY 3)

 Strings can be converted to upper/lower case


 toupper() and tolower() used
 Helps in formatting text

🔹 Code
toupper("bab")
tolower("BAB")

🔹 Output
[1] "BAB"
[1] "bab"

🔹 Accessing Characters
🔹 Definition (ANY 3)

 Characters can be accessed using index


 Index starts from 1
 Used to extract characters

🔹 Code
substr("Bab",1,2)

🔹 Output
[1] "Ba"

🔹 Uses

 Store names and messages


 Used in data processing
 Used in reports
 Used in real-world applications
 Helps in text manipulation

🔹 Conclusion
 Character strings are important for handling and processing text data in R

24, Explain Classes in R

🔹 Definition (Write ANY 3–4)

 A class in R defines the type of an object


 It tells how the data is stored and used
 Every object in R belongs to a class
 Classes help to identify data type

🔹 Introduction

 In R, everything is an object
 Each object has a class
 Class helps to understand data structure
 Used in data handling and analysis

🔹 Checking Class
🔹 Definition (ANY 3)

 Class of object is found using class()


 It shows type of data
 Helps in understanding data

🔹 Code
x <- 10

class(x)
🔹 Output
[1] "numeric"

🔹 Different Classes in R
🔹 Definition (ANY 3)

 R supports many classes


 Common classes include numeric, character, logical
 Used to represent different data types

🔹 Code
class("Bab")
class(TRUE)

🔹 Output
[1] "character"
[1] "logical"

🔹 Changing Class
🔹 Definition (ANY 3)

 Class can be converted using functions


 Example: [Link](), [Link]()
 Used to change data type

🔹 Code
x <- "10"

[Link](x)

🔹 Output
[1] 10

🔹 Uses

 Identify data type


 Helps in data processing
 Used in conversions
 Improves program understanding
 Used in analysis

🔹 Conclusion

 Classes are important for understanding and managing data types in R


25, Explain Generating Sequences in R

🔹 Definition (Write ANY 3–4)

 Generating sequences means creating ordered series of values


 It is used to produce continuous numeric data
 Sequences can be created using : and seq()
 Used in loops and vector operations

🔹 Introduction

 Sequences are important in R programming


 Used to generate ranges of numbers
 Helps in iteration and data creation
 Widely used in vector operations

🔹 Using Colon Operator (:)


🔹 Definition (ANY 3)

 : is used to create simple sequences


 Generates numbers from start to end
 Used for integer sequences

🔹 Code
numbers <- 1:5

numbers

🔹 Output
[1] 1 2 3 4 5

🔹 Reverse Sequence
🔹 Definition (ANY 3)

 Sequence can be generated in reverse order


 Start value is greater than end value
 Useful for countdown
🔹 Code
numbers <- 5:1

numbers

🔹 Output
[1] 5 4 3 2 1

🔹 Decimal Sequence
🔹 Definition (ANY 3)

 Decimal values can be used in sequences


 Increments by 1
 Last value may not be included

🔹 Code
numbers <- 1.5:5.5

numbers

🔹 Output
[1] 1.5 2.5 3.5 4.5 5.5

🔹 Using seq() Function


🔹 Definition (ANY 3)

 seq() generates sequences with control


 Allows specifying step size
 Used for flexible sequences

🔹 Code
numbers <- seq(from = 0, to = 10, by = 2)

numbers

🔹 Output
[1] 0 2 4 6 8 10
🔹 Sequence with Length
🔹 Definition (ANY 3)

 [Link] defines number of elements


 Automatically generates values
 Useful when size is fixed

🔹 Code
numbers <- seq(from = 1, to = 10, [Link] = 5)

numbers

🔹 Output
[1] 1.00 3.25 5.50 7.75 10.00

🔹 Uses

 Used in loops
 Used in vector creation
 Helps in data generation
 Used in calculations
 Used in real-world applications

🔹 Conclusion

 Generating sequences is important for creating ordered data in R programming


26, Explain Vectors and Subscripts in R

🔹 Definition (Write ANY 3–4)

 Subscripts are used to access elements of a vector


 They represent the position (index) of elements
 In R, indexing starts from 1
 Subscripts help to retrieve and manipulate data

🔹 Introduction

 Vectors store multiple values


 Subscripts help to access specific values
 Used in data selection and operations
 Important for data analysis

🔹 Accessing Elements using Subscripts


🔹 Definition (ANY 3)

 Elements accessed using square brackets [ ]


 Index indicates position
 Used to retrieve values

🔹 Code
x <- c(10, 20, 30, 40)

x[2]

🔹 Output
[1] 20

🔹 Access Multiple Elements


🔹 Definition (ANY 3)

 Multiple elements accessed using c()


 Can select more than one index
 Useful for grouping values
🔹 Code
x[c(1,3)]

🔹 Output
[1] 10 30

🔹 Negative Subscripts
🔹 Definition (ANY 3)

 Negative index excludes elements


 Used to remove values
 Returns remaining elements

🔹 Code
x[-2]

🔹 Output
[1] 10 30 40

🔹 Logical Subscripts
🔹 Definition (ANY 3)

 Logical values TRUE/FALSE used


 TRUE selects element
 FALSE ignores element

🔹 Code
x[c(TRUE, FALSE, TRUE, FALSE)]

🔹 Output
[1] 10 30

🔹 Using Conditions
🔹 Definition (ANY 3)

 Conditions used inside subscripts


 Returns values satisfying condition
 Used in filtering data

🔹 Code
x[x > 20]

🔹 Output
[1] 30 40

🔹 Subscripts Assignment
🔹 Definition (ANY 3)

 Values can be modified using subscripts


 Used to update elements
 Helps in data manipulation

🔹 Code
x[1] <- 100

🔹 Output
[1] 100 20 30 40

🔹 Uses

 Access specific elements


 Modify vector values
 Filter data
 Perform operations
 Used in real-world applications

🔹 Conclusion

 Subscripts are essential for accessing and manipulating vector elements in R


27, Explain Extracting Elements of a Vector using Subscripts in R

🔹 Definition (Write ANY 3–4)

 Extracting elements means retrieving values from a vector


 It is done using subscripts (index values)
 Subscripts specify position of elements
 Used to access single or multiple values

🔹 Introduction

 Vectors store multiple values


 Extraction helps to get required data
 Done using square brackets [ ]
 Important in data analysis and filtering

🔹 Extract Single Element


🔹 Definition (ANY 3)

 A single value can be extracted using index


 Index starts from 1 in R
 Used to access specific element

🔹 Code
x <- c(10, 20, 30, 40)

x[3]

🔹 Output
[1] 30

🔹 Extract Multiple Elements


🔹 Definition (ANY 3)

 Multiple elements extracted using c()


 Allows selection of multiple positions
 Useful for grouping values

🔹 Code
x[c(1,4)]

🔹 Output
[1] 10 40

🔹 Extract Range of Elements


🔹 Definition (ANY 3)

 Range extraction uses : operator


 Selects continuous elements
 Used for slicing data

🔹 Code
x[2:4]

🔹 Output
[1] 20 30 40

🔹 Extract Using Negative Index


🔹 Definition (ANY 3)

 Negative index excludes elements


 Used to remove specific values
 Returns remaining elements

🔹 Code
x[-3]

🔹 Output
[1] 10 20 40
🔹 Extract Using Logical Values
🔹 Definition (ANY 3)

 Logical values TRUE/FALSE used


 TRUE selects element
 FALSE ignores element

🔹 Code
x[c(TRUE, FALSE, TRUE, FALSE)]

🔹 Output
[1] 10 30

🔹 Extract Using Condition


🔹 Definition (ANY 3)

 Conditions used inside brackets


 Returns values satisfying condition
 Used for filtering

🔹 Code
x[x > 20]

🔹 Output
[1] 30 40

🔹 Uses

 Retrieve specific data


 Filter values
 Select range of elements
 Used in data analysis
 Improves data handling

🔹 Conclusion

 Extracting elements using subscripts is important for accessing and filtering data in
vectors
28, Explain Logical Subscripts in R

🔹 Definition (Write ANY 3–4)

 Logical subscripts use TRUE and FALSE values to access data


 TRUE means select element
 FALSE means ignore element
 Used to filter vector elements

🔹 Introduction

 Logical subscripts are used in vector operations


 Helps to select data based on conditions
 Works with logical values
 Important in data filtering

🔹 Using Logical Values


🔹 Definition (ANY 3)

 Logical values are TRUE or FALSE


 Used inside brackets [ ]
 Select elements based on position

🔹 Code
x <- c(10, 20, 30, 40)

x[c(TRUE, FALSE, TRUE, FALSE)]

🔹 Output
[1] 10 30
🔹 Using Conditions
🔹 Definition (ANY 3)

 Conditions return logical values


 Used to filter data
 Returns elements satisfying condition

🔹 Code
x[x > 20]

🔹 Output
[1] 30 40

🔹 Logical Operations
🔹 Definition (ANY 3)

 Logical operators like &, | used


 Combine conditions
 Helps in advanced filtering

🔹 Code
x[x > 10 & x < 40]

🔹 Output
[1] 20 30

🔹 Recycling Rule
🔹 Definition (ANY 3)

 Logical vector is recycled if shorter


 Repeats values automatically
 Must match vector length

🔹 Code
x[c(TRUE, FALSE)]

🔹 Output
[1] 10 30
🔹 Uses

 Filter data
 Select specific values
 Used in conditions
 Helps in data analysis
 Improves efficiency

🔹 Conclusion

 Logical subscripts are important for filtering and selecting data efficiently in R
29, Explain Scalars, Vectors, Arrays, and Matrices in R

🔹 Definition (Write ANY 3–4)

 Data structures are used to store and organize data


 R provides different structures for different purposes
 Each structure has its own features and usage
 They help in efficient data handling

🔹 Introduction

 R supports multiple data structures


 Used for storing single and multiple values
 Important in data analysis
 Includes scalar, vector, matrix, and array

🔹 1. Scalar
🔹 Definition (ANY 3)

 A scalar is a single value


 It stores only one element
 It is the simplest data type

🔹 Code
x <- 10

🔹 Output
[1] 10

🔹 2. Vector
🔹 Definition (ANY 3)

 A vector stores multiple values


 All elements are of same type
 Created using c()
🔹 Code
v <- c(1,2,3)

🔹 Output
[1] 1 2 3

🔹 3. Matrix
🔹 Definition (ANY 3)

 Matrix is a 2D data structure


 Contains rows and columns
 All elements are same type

🔹 Code
m <- matrix(c(1,2,3,4), nrow=2)

🔹 Output
[,1] [,2]
[1,] 1 3
[2,] 2 4

🔹 4. Array
🔹 Definition (ANY 3)

 Array is multi-dimensional structure


 Extension of matrix
 Stores same type elements

🔹 Code
a <- array(1:8, dim=c(2,2,2))

a
🔹 Output (sample)
,,1
[,1] [,2]
[1,] 1 3
[2,] 2 4

,,2
[,1] [,2]
[1,] 5 7
[2,] 6 8

🔹 Comparison Table
Structure Data Type Dimension Example
Scalar Single 0D x = 10
Vector Same type 1D c(1,2,3)
Matrix Same type 2D matrix()
Array Same type Multi-D array()

🔹 Uses

 Store data efficiently


 Perform calculations
 Used in analysis
 Helps in data organization
 Used in real-world applications

🔹 Conclusion

 Scalars, vectors, matrices, and arrays are important for storing and processing data
in R
30, Explain Adding and Deleting Vector Elements in R

🔹 Definition (Write ANY 3–4)

 Adding means inserting new elements into a vector


 Deleting means removing elements from a vector
 Done using indexing and functions
 Used to modify vector data

🔹 Introduction

 Vectors store multiple values


 Sometimes we need to update or modify data
 R provides methods to add and delete elements
 Important for data manipulation

🔹 Adding Elements to Vector


🔹 Definition (ANY 3)

 Elements can be added using c()


 Can add at beginning, middle, or end
 Used to expand vector

🔹 Code (Add at End)


x <- c(1,2,3)

x <- c(x, 4)

🔹 Output
[1] 1 2 3 4

🔹 Code (Add at Beginning)


x <- c(0, x)

x
🔹 Output
[1] 0 1 2 3 4

🔹 Code (Add at Specific Position)


x <- append(x, 10, after = 2)

🔹 Output
[1] 0 1 10 2 3 4

🔹 Deleting Elements from Vector


🔹 Definition (ANY 3)

 Elements removed using negative index


 Creates updated vector
 Used to delete unwanted values

🔹 Code
x <- c(1,2,3,4)

x <- x[-2]

🔹 Output
[1] 1 3 4

🔹 Deleting Multiple Elements


🔹 Definition (ANY 3)

 Multiple elements removed using c()


 Used for deleting more than one value
 Helps in data cleaning

🔹 Code
x <- c(1,2,3,4,5)

x <- x[-c(2,4)]
x

🔹 Output
[1] 1 3 5

🔹 Uses

 Modify vector data


 Add new values
 Remove unwanted values
 Used in data cleaning
 Used in real-world applications

🔹 Conclusion

 Adding and deleting elements helps in dynamic modification of vectors in R


31, Explain Vector Arithmetic and Logical Operations in R

🔹 Definition (Write ANY 3–4)

 Vector arithmetic means performing mathematical operations on vectors


 Logical operations mean applying conditions on vectors
 Operations are performed element-wise
 Used for data analysis and calculations

🔹 Introduction

 Vectors support mathematical and logical operations


 Operations are applied to each element of vector
 No need for loops → faster execution
 Important in data processing

🔹 Vector Arithmetic Operations


🔹 Definition (ANY 3)

 Arithmetic operations include +, -, *, /


 Performed element-wise
 Vectors must be same length or recycled

🔹 Addition
x <- c(1,2,3)
y <- c(4,5,6)

x+y
🔹 Output
[1] 5 7 9

🔹 Subtraction
x-y
🔹 Output
[1] -3 -3 -3

🔹 Multiplication
x*y
🔹 Output
[1] 4 10 18

🔹 Division
x/y
🔹 Output
[1] 0.25 0.40 0.50

🔹 Vector with Scalar


🔹 Definition (ANY 3)

 Scalar is a single value


 Operation applies to all elements
 Useful for scaling data

🔹 Code
x*2
🔹 Output
[1] 2 4 6

🔹 Recycling Rule
🔹 Definition (ANY 3)

 Short vector is repeated


 Matches length of longer vector
 Used automatically in operations

🔹 Code
c(1,2,3,4) + c(1,2)
🔹 Output
[1] 2 4 4 6

🔹 Logical Operations
🔹 Definition (ANY 3)

 Logical operations return TRUE or FALSE


 Used to compare values
 Helps in filtering data
🔹 Greater Than
x>2
🔹 Output
[1] FALSE FALSE TRUE

🔹 Equal To
x == 2
🔹 Output
[1] FALSE TRUE FALSE

🔹 Logical Operators
🔹 Definition (ANY 3)

 Operators include &, |, !


 Used to combine conditions
 Used in filtering

🔹 Code
x>1&x<3
🔹 Output
[1] FALSE TRUE FALSE

🔹 Uses

 Perform calculations
 Apply conditions
 Filter data
 Used in analysis
 Improves efficiency

🔹 Conclusion

 Vector arithmetic and logical operations are important for efficient data processing in
R
32, Explain Vector Indexing and Common Vector Operations in R

🔹 Definition (Write ANY 3–4)

 Vector indexing is used to access elements using position


 It helps to retrieve and modify data
 Common operations are used to process vector values
 These are important for data manipulation in R

🔹 Introduction

 Vectors store multiple values


 Indexing helps to access specific values
 Operations help to analyze data
 Widely used in real-time applications

🔹 Vector Indexing
🔹 Definition (ANY 3)

 Indexing means accessing elements using position


 Uses square brackets [ ]
 Index starts from 1

🔹 Code
x <- c(10,20,30,40)

x[2]

🔹 Output
[1] 20

🔹 Multiple Indexing
🔹 Definition (ANY 3)

 Multiple elements accessed using c()


 Helps to select group values
 Used in data selection

🔹 Code
x[c(1,3)]

🔹 Output
[1] 10 30

🔹 Negative Indexing
🔹 Definition (ANY 3)

 Negative index excludes elements


 Used to remove values
 Returns remaining elements

🔹 Code
x[-2]

🔹 Output
[1] 10 30 40

🔹 Logical Indexing
🔹 Definition (ANY 3)

 Uses TRUE/FALSE values


 TRUE selects element
 Used for filtering

🔹 Code
x[x > 20]

🔹 Output
[1] 30 40

🔹 Common Vector Operations


🔸 1. Sum
🔹 Definition (ANY 3)

 sum() adds all elements


 Used to calculate total
 Works on numeric vectors

🔹 Code
sum(x)

🔹 Output
[1] 100

🔸 2. Mean
🔹 Definition (ANY 3)

 mean() finds average


 Used in statistics
 Works on numeric data

🔹 Code
mean(x)

🔹 Output
[1] 25

🔸 3. Max & Min


🔹 Definition (ANY 3)

 max() finds largest value


 min() finds smallest value
 Used in analysis

🔹 Code
max(x)
min(x)
🔹 Output
[1] 40
[1] 10

🔸 4. Sorting
🔹 Definition (ANY 3)

 sort() arranges values


 Can be ascending or descending
 Used for ordering data

🔹 Code
sort(x)

🔹 Output
[1] 10 20 30 40

🔸 5. Length
🔹 Definition (ANY 3)

 length() gives number of elements


 Used to measure size
 Important in operations

🔹 Code
length(x)

🔹 Output
[1] 4

🔹 Uses

 Access and modify data


 Perform calculations
 Analyze values
 Used in data processing
 Used in real-world applications
🔹 Conclusion

 Vector indexing and operations are essential for handling and analyzing data
efficiently in R
33, Explain Math Functions in R

🔹 Definition (Write ANY 3–4)

 Math functions are used to perform mathematical operations in R


 They are built-in functions provided by R
 Used for calculation and data analysis
 Help to reduce manual work and errors

🔹 Introduction

 R provides many mathematical functions


 Used in basic and advanced calculations
 Important for statistical analysis
 Widely used in real-world applications

🔹 1. Absolute Function
🔹 Definition

 Returns positive value of number


 Removes negative sign
 Always gives non-negative result

🔹 Syntax
abs(x)
🔹 Example
abs(-10)
🔹 Output
[1] 10

🔹 2. Square Root
🔹 Definition

 Finds square root of number


 Works on numeric values
 Used in calculations

🔹 Syntax
sqrt(x)
🔹 Example
sqrt(16)
🔹 Output
[1] 4

🔹 3. Power Function
🔹 Definition

 Raises number to power


 Uses ^ operator
 Used in scientific calculations

🔹 Syntax
x^y
🔹 Example
2^3
🔹 Output
[1] 8

🔹 4. Logarithmic Function
🔹 Definition

 Calculates logarithm of number


 Default base is e
 Used in statistics

🔹 Syntax
log(x)
🔹 Example
log(10)
🔹 Output
[1] 2.302585

🔹 5. Exponential Function
🔹 Definition

 Calculates e^x value


 Used in advanced math
 Important in statistics
🔹 Syntax
exp(x)
🔹 Example
exp(1)
🔹 Output
[1] 2.718282

🔹 6. Rounding Functions
🔹 Definition

 Used to round numbers


 Includes round, floor, ceiling
 Helps in formatting values

🔹 Syntax
round(x)
floor(x)
ceiling(x)
🔹 Example
round(3.6)
floor(3.6)
ceiling(3.2)
🔹 Output
[1] 4
[1] 3
[1] 4

🔹 7. Minimum and Maximum


🔹 Definition

 Finds smallest and largest value


 Used in data analysis
 Works on vectors

🔹 Syntax
min(x)
max(x)
🔹 Example
x <- c(2,5,1,9)

min(x)
max(x)
🔹 Output
[1] 1
[1] 9

🔹 8. Sum and Product


🔹 Definition

 sum() adds all elements


 prod() multiplies elements
 Used in calculations

🔹 Syntax
sum(x)
prod(x)
🔹 Example
x <- c(2,3,4)

sum(x)
prod(x)
🔹 Output
[1] 9
[1] 24

🔹 9. Mean (Average)
🔹 Definition

 Calculates average value


 Used in statistics
 Works on numeric data

🔹 Syntax
mean(x)
🔹 Example
x <- c(2,4,6)

mean(x)
🔹 Output
[1] 4
🔹 10. Cumulative Functions
🔹 Definition

 cumsum() gives cumulative sum


 cumprod() gives cumulative product
 Used in analysis

🔹 Syntax
cumsum(x)
cumprod(x)
🔹 Example
x <- c(1,2,3)

cumsum(x)
cumprod(x)
🔹 Output
[1] 1 3 6
[1] 1 2 6

🔹 Conclusion

 Math functions are essential for performing calculations and data analysis in R
34, Explain Cumulative Sum and Cumulative Product in R

🔹 Definition (Write ANY 3–4)

 Cumulative sum calculates the running total of elements


 Cumulative product calculates the running multiplication of elements
 These functions work on vectors
 Used in data analysis and calculations

🔹 Introduction

 Cumulative functions help in step-by-step calculations


 They return values based on previous results
 Useful in statistics and analysis
 Implemented using cumsum() and cumprod()

🔹 1. Cumulative Sum
🔹 Definition (ANY 3)

 cumsum() calculates running total


 Adds each element with previous sum
 Returns vector of cumulative values

🔹 Syntax
cumsum(x)

🔹 Example
x <- c(1,2,3,4)

cumsum(x)

🔹 Output
[1] 1 3 6 10

👉 Explanation:
1
1+2 = 3
3+3 = 6
6+4 = 10

🔹 2. Cumulative Product
🔹 Definition (ANY 3)

 cumprod() calculates running multiplication


 Multiplies each element with previous result
 Returns cumulative product values

🔹 Syntax
cumprod(x)

🔹 Example
x <- c(1,2,3,4)

cumprod(x)

🔹 Output
[1] 1 2 6 24

👉 Explanation:
1
1×2 = 2
2×3 = 6
6×4 = 24

🔹 Difference Between cumsum() and cumprod()


Function Operation Example Output

cumsum() Addition 1 3 6 10

cumprod() Multiplication 1 2 6 24

🔹 Uses

 Used in financial calculations


 Used in statistics
 Used in data analysis
 Helps track running totals
 Used in real-world applications

🔹 Conclusion

 Cumulative functions are useful for step-by-step calculations in R


35, Explain Minima and Maxima in R

🔹 Definition (Write ANY 3–4)

 Minima means finding the smallest value in data


 Maxima means finding the largest value in data
 Used to identify extreme values
 Implemented using min() and max() functions

🔹 Introduction

 In data analysis, we often need minimum and maximum values


 R provides built-in functions for this
 Works on vectors and datasets
 Useful in statistics and decision making

🔹 Minimum Value
🔹 Definition (ANY 3)

 min() finds the smallest element


 Works on numeric vectors
 Returns a single value

🔹 Syntax
min(x)

🔹 Example
x <- c(10, 5, 20, 3)

min(x)

🔹 Output
[1] 3
🔹 Maximum Value
🔹 Definition (ANY 3)

 max() finds the largest element


 Works on numeric vectors
 Returns a single value

🔹 Syntax
max(x)

🔹 Example
x <- c(10, 5, 20, 3)

max(x)

🔹 Output
[1] 20

🔹 Using Both Together


🔹 Code
x <- c(4,8,1,9)

min(x)
max(x)

🔹 Output
[1] 1
[1] 9
36, Explain Calculating Probability in R

🔹 Definition (Write ANY 3–4)

 Probability is the chance of an event occurring


 It is a value between 0 and 1
 0 means impossible, 1 means certain
 Used in statistics and data analysis

🔹 Introduction

 R provides functions to calculate probability


 Used in statistical models and predictions
 Helps in decision making
 Works with different distributions

🔹 Basic Probability Formula


🔹 Definition (ANY 3)

 Probability = Favorable outcomes / Total outcomes


 Used for simple calculations
 Represents likelihood of event

🔹 Syntax
P = favorable / total

🔹 Example
favorable <- 2
total <- 6

P <- favorable / total


P

🔹 Output
[1] 0.3333333
🔹 Using sample() Function
🔹 Definition (ANY 3)

 sample() is used for random selection


 Helps simulate probability
 Used in experiments

🔹 Syntax
sample(x, size)

🔹 Example
sample(1:6, 1)

🔹 Output (example)
[1] 4

🔹 Using runif() Function


🔹 Definition (ANY 3)

 runif() generates random numbers


 Values between 0 and 1
 Used for probability simulation

🔹 Syntax
runif(n)

🔹 Example
runif(3)

🔹 Output (example)
[1] 0.23 0.78 0.45

🔹 Probability with Conditions


🔹 Definition (ANY 3)

 Conditions used to filter outcomes


 Logical operations applied
 Used to calculate probability
🔹 Code
x <- c(1,2,3,4,5,6)

sum(x > 3) / length(x)

🔹 Output
[1] 0.5

🔹 Uses

 Used in predictions
 Used in statistics
 Helps in decision making
 Used in machine learning
 Used in real-world problems

🔹 Conclusion

 Probability in R helps to analyze uncertainty and make predictions

CALCULUS, FUNCTIONS FOR STATISTICAL DISTRIBUTIONS NOT TAKE


FEELS HARD
37, Explain Scatter Plot in R

🔹 Definition (Write ANY 3–4)

 A scatter plot is used to display relationship between two variables


 It shows data points on a 2D graph
 Each point represents (x, y) values
 Used to identify patterns and trends

🔹 Introduction

 Scatter plot is used in data visualization


 Helps to understand correlation between variables
 Widely used in statistics and analysis
 Created using plot() function in R

🔹 Syntax
plot(x, y)

🔹 Basic Scatter Plot


🔹 Definition (ANY 3)

 Uses two numeric vectors


 X-axis and Y-axis represent variables
 Displays points on graph

🔹 Code
x <- c(1,2,3,4,5)
y <- c(2,4,6,8,10)

plot(x, y)
🔹 Output

🔹 Scatter Plot with Labels


🔹 Definition (ANY 3)

 Labels improve readability


 Add title and axis names
 Helps in understanding graph

🔹 Code
plot(x, y,
main = "Scatter Plot",
xlab = "X Values",
ylab = "Y Values")

🔹 Output
🔹 Scatter Plot with Color
🔹 Definition (ANY 3)

 Colors improve visualization


 Makes graph attractive
 Helps differentiate data

🔹 Code
plot(x, y, col = "blue")

🔹 Output

🔹 Scatter Plot with Points Style


🔹 Definition (ANY 3)

 Different symbols can be used


 Controlled using pch
 Improves visualization

🔹 Code
plot(x, y, pch = 16)

🔹 Output
👉 Solid dot points

🔹 Uses

 Shows relationship between variables


 Identifies trends
 Used in data analysis
 Helps in predictions
 Used in real-world applications

🔹 Conclusion

 Scatter plots are useful for visualizing relationships between variables in R


38, Explain Box Plot in R

🔹 Definition (Write ANY 3–4)

 A box plot is used to display distribution of data


 It shows minimum, maximum, median, and quartiles
 Also called box and whisker plot
 Used to identify outliers and spread of data

🔹 Introduction

 Box plot is an important data visualization tool


 Summarizes data using five-number summary
 Helps to understand data distribution
 Created using boxplot() function in R

🔹 Syntax
boxplot(x)

🔹 Basic Box Plot


🔹 Definition (ANY 3)

 Uses a single numeric vector


 Displays data distribution
 Shows median and quartiles

🔹 Code
x <- c(10, 20, 30, 40, 50)

boxplot(x)

🔹 Output
🔹 Box Plot with Title & Labels
🔹 Definition (ANY 3)

 Labels improve readability


 Adds title and axis names
 Helps understanding

🔹 Code
boxplot(x,
main = "Box Plot",
ylab = "Values")

🔹 Output
🔹 Box Plot with Color
🔹 Definition (ANY 3)

 Colors improve visualization


 Makes graph attractive
 Helps highlight data

🔹 Code
boxplot(x, col = "blue")

🔹 Output

🔹 Multiple Box Plots


🔹 Definition (ANY 3)

 Used to compare multiple datasets


 Shows variation between groups
 Useful in analysis

🔹 Code
a <- c(10,20,30)
b <- c(15,25,35)

boxplot(a, b)
🔹 Output

🔹 Important Terms in Box Plot


🔹 Definition (ANY 3)

 Minimum → smallest value


 Q1 → lower quartile
 Median (Q2) → middle value
 Q3 → upper quartile
 Maximum → largest value

🔹 Uses

 Understand data distribution


 Detect outliers
 Compare datasets
 Used in statistics
 Used in real-world analysis

🔹 Conclusion

 Box plot is useful for summarizing and visualizing data distribution in R

SCATTER PLOTS AND BOX ANDWHISKER PLOTS TOGETHER AM SKIPPED


THIS TOPIC ALSO
39, Explain Customization of Plots in R

🔹 Definition (Write ANY 3–4)

 Customization of plots means modifying the appearance of graphs


 It improves clarity and presentation
 Helps to highlight important data
 Makes visualization attractive and understandable

🔹 Introduction

 Default plots are simple


 Customization improves data interpretation
 R provides many options for customization
 Widely used in data visualization and analysis

🔹 Types of Customization in R

🔸 1. Title (main)
🔹 Definition (ANY 3)

 Title describes the graph


 Helps understand purpose
 Added using main

🔹 Syntax
plot(x, y, main = "Title")
🔹 Example
x <- c(1,2,3)
y <- c(2,4,6)

plot(x, y, main = "My Plot")


🔹 Output

🔸 2. Axis Labels (xlab, ylab)


🔹 Definition (ANY 3)

 Labels describe axes


 Improve readability
 Show meaning of data

🔹 Syntax
plot(x, y, xlab = "X-axis", ylab = "Y-axis")
🔹 Example
plot(x, y,
xlab = "Values of X",
ylab = "Values of Y")
🔹 Output

🔸 3. Colors (col)
🔹 Definition (ANY 3)

 Adds color to graph


 Makes graph attractive
 Helps distinguish data

🔹 Syntax
plot(x, y, col = "color")
🔹 Example
plot(x, y, col = "red")
🔹 Output
🔸 4. Legend (legend())
🔹 Definition (ANY 3)

 Explains symbols and colors


 Helps identify data
 Important for multiple datasets

🔹 Syntax
legend("position", legend = "text", col = "color", pch = value)
🔹 Example
plot(x, y, col = "blue", pch = 16)

legend("topleft",
legend = "Data",
col = "blue",
pch = 16)
🔹 Output

🔸 5. Point Style (pch)


🔹 Definition (ANY 3)

 Changes shape of points


 Improves visualization
 Different styles available

🔹 Syntax
plot(x, y, pch = value)
🔹 Example
plot(x, y, pch = 17)

🔹 Output

👉 Triangle shaped points

🔸 6. Line Type & Width (lty, lwd)


🔹 Definition (ANY 3)

 Controls line style


 lty → line type
 lwd → line thickness

🔹 Example
plot(x, y, type = "l", lty = 2, lwd = 3)
🔹 Output

👉 Dashed thick line

🔸 7. Axis Limits (xlim, ylim)


🔹 Definition (ANY 3)

 Controls range of axes


 Limits data display
 Improves focus

🔹 Syntax
plot(x, y, xlim = c(0,10), ylim = c(0,10))

🔹 Output

👉 Graph within specified limits


🔸 8. Grid (grid())
🔹 Definition (ANY 3)

 Adds grid lines


 Improves readability
 Helps in data comparison

🔹 Code
plot(x, y)
grid()

🔹 Output

👉 Graph with grid lines

🔹 Uses

 Improves graph appearance


 Makes data understandable
 Helps in presentations
 Used in analysis
 Used in real-world applications

🔹 Conclusion

 Customization of plots helps to create clear, attractive, and meaningful graphs in R


40, Explain Measures of Central Tendency in R

🔹 Definition (Write ANY 3–4)

 Measures of central tendency are used to find the central value of data
 They represent the average or typical value
 Help to summarize data easily
 Common measures are Mean, Median, and Mode

🔹 Introduction

 Central tendency gives a single value representing dataset


 Helps in understanding data quickly
 Used in statistics and analysis
 R provides functions to calculate these measures

🔹 1. Mean (Average)
🔹 Definition (ANY 3)

 Mean is the average of all values


 Calculated as sum / number of elements
 Most widely used measure

🔹 Syntax
mean(x)

🔹 Example
x <- c(10, 20, 30, 40)

mean(x)

🔹 Output
[1] 25
🔹 2. Median
🔹 Definition (ANY 3)

 Median is the middle value


 Data must be arranged in order
 Divides data into two equal parts

🔹 Syntax
median(x)

🔹 Example
x <- c(10, 20, 30, 40, 50)

median(x)

🔹 Output
[1] 30

🔹 3. Mode (Easy Method 😏🔥)


🔹 Definition (ANY 3)

 Mode is the most frequently occurring value


 Shows highest repetition
 Used to find common value

🔹 Syntax (Simple)
names(sort(table(x), decreasing = TRUE))[1]

🔹 Example
x <- c(2,3,3,5,6)

names(sort(table(x), decreasing = TRUE))[1]

🔹 Output
[1] 3

🔹 Uses

 Summarize data
 Used in statistics
 Helps in decision making
 Used in analysis
 Used in real-world applications

🔹 Conclusion

 Measures of central tendency help to identify the central value of data effectively in
R
41, Explain Measures of Variability in R

🔹 Definition (Write ANY 3–4)

 Measures of variability show how data is spread


 They indicate variation or dispersion in data
 Help to understand consistency of data
 Common measures are Range, Variance, Standard Deviation

🔹 Introduction

 Central tendency gives center value


 Variability shows how far values spread
 Important for data analysis and comparison
 R provides functions to calculate variability

🔹 1. Range
🔹 Definition (ANY 3)

 Range is the difference between max and min values


 Shows total spread of data
 Simple measure of variability

🔹 Syntax
range(x)

🔹 Example
x <- c(10, 20, 30, 40)

range(x)

🔹 Output
[1] 10 40

👉 (Min = 10, Max = 40)


🔹 2. Variance
🔹 Definition (ANY 3)

 Variance measures average squared deviation from mean


 Indicates how far values are spread
 Larger value → more variation

🔹 Syntax
var(x)

🔹 Example
x <- c(10, 20, 30)

var(x)

🔹 Output
[1] 100

🔹 3. Standard Deviation
🔹 Definition (ANY 3)

 Standard deviation is square root of variance


 Measures spread in same unit as data
 Most commonly used measure

🔹 Syntax
sd(x)

🔹 Example
x <- c(10, 20, 30)

sd(x)

🔹 Output
[1] 10

🔹 Combined Example
x <- c(5,10,15,20)
range(x)
var(x)
sd(x)

🔹 Output
[1] 5 20
[1] 41.67
[1] 6.45

🔹 Uses

 Measure data spread


 Compare datasets
 Identify consistency
 Used in statistics
 Used in analysis

🔹 Conclusion

 Measures of variability help to understand dispersion of data in R


42, Explain Skewness and Kurtosis in R

🔹 Definition (Write ANY 3–4)

 Skewness and kurtosis are used to describe shape of data distribution


 Skewness shows symmetry of data
 Kurtosis shows peakedness or flatness of data
 Used in statistical analysis

🔹 Introduction

 In statistics, shape of data is important


 Skewness and kurtosis help to understand distribution
 Used along with mean and variance
 R provides functions to calculate these

🔹 1. Skewness
🔹 Definition (ANY 3)

 Skewness measures asymmetry of distribution


 If data is symmetric → skewness = 0
 Positive skew → right tail longer
 Negative skew → left tail longer

🔹 Types of Skewness

 Positive Skewness → tail on right


 Negative Skewness → tail on left
 Zero Skewness → symmetric

🔹 Syntax (using library)


library(moments)
skewness(x)

🔹 Example
library(moments)

x <- c(1,2,2,3,4,10)
skewness(x)

🔹 Output
[1] Positive value (example: 1.2)

👉 Indicates positive skew

🔹 2. Kurtosis
🔹 Definition (ANY 3)

 Kurtosis measures peakedness of distribution


 Shows how data is concentrated
 Helps identify outliers

🔹 Types of Kurtosis

 Leptokurtic → high peak


 Platykurtic → flat distribution
 Mesokurtic → normal shape

🔹 Syntax
kurtosis(x)
🔹 Example
kurtosis(x)

🔹 Output
[1] Value (example: 3.5)

🔹 Uses

 Understand data distribution


 Identify skewness in data
 Detect outliers
 Used in statistics
 Used in analysis

🔹 Conclusion

 Skewness and kurtosis help to analyze shape of data distribution in R


43, Explain Summary Functions in R

🔹 Definition (Write ANY 3–4)

 Summary functions are used to summarize data quickly


 They provide statistical details of dataset
 Help to understand data distribution
 Used in data analysis

🔹 Introduction

 In R, summary functions give quick overview of data


 Used for basic statistical analysis
 Helps in decision making
 Common functions include mean, median, summary

🔹 1. summary() Function
🔹 Definition (ANY 3)

 Provides min, max, median, mean, quartiles


 Works on vectors and data frames
 Gives quick overview

🔹 Syntax
summary(x)

🔹 Example
x <- c(10, 20, 30, 40, 50)

summary(x)

🔹 Output
Min. :10
1st Qu.:20
Median :30
Mean :30
3rd Qu.:40
Max. :50
🔹 2. mean() Function
🔹 Definition (ANY 3)

 Calculates average
 Most common measure
 Used in analysis

🔹 Example
mean(x)
🔹 Output
[1] 30

🔹 3. median() Function
🔹 Definition (ANY 3)

 Finds middle value


 Divides dataset
 Used in statistics

🔹 Example
median(x)
🔹 Output
[1] 30

🔹 4. min() and max()


🔹 Definition (ANY 3)

 Finds smallest and largest value


 Used to identify range
 Important for analysis

🔹 Example
min(x)
max(x)
🔹 Output
[1] 10
[1] 50
🔹 5. sd() and var()
🔹 Definition (ANY 3)

 sd() → standard deviation


 var() → variance
 Measures data spread

🔹 Example
sd(x)
var(x)

🔹 Output
[1] 15.81
[1] 250

🔹 Uses

 Quick data analysis


 Summarize dataset
 Used in statistics
 Helps in decision making
 Used in real-world applications

🔹 Conclusion

 Summary functions help to analyze and understand data quickly in R


44, Explain Describe Functions and Descriptive Statistics by Group in R

🔹 Definition (Write ANY 3–4)

 Describe functions provide detailed statistical summary of data


 Include values like mean, median, sd, min, max
 Group statistics analyze data based on categories
 Used in data analysis and comparison

🔹 Introduction

 Basic summary gives limited info


 Describe functions give full detailed analysis
 Group statistics help compare different groups
 Used in real-world data analysis

🔹 1. Describe Function
🔹 Definition (ANY 3)

 Gives detailed statistics of dataset


 Includes mean, sd, min, max, etc.
 Available using psych package

🔹 Syntax
library(psych)
describe(x)

🔹 Example
library(psych)

x <- c(10,20,30,40,50)

describe(x)

🔹 Output (Simple)
mean = 30
sd = 15.81
min = 10
max = 50

🔹 2. Descriptive Statistics by Group


🔹 Definition (ANY 3)

 Data is divided into groups


 Statistics calculated for each group
 Helps in comparison

🔹 Syntax
tapply(x, group, function)

🔹 Example
marks <- c(80,90,70,60,85)
group <- c("A","A","B","B","A")

tapply(marks, group, mean)

🔹 Output
A B
85 65

🔹 Another Method (aggregate)


🔹 Syntax
aggregate(x ~ group, data, mean)

🔹 Example
data <- [Link](
marks = c(80,90,70,60,85),
group = c("A","A","B","B","A")
)

aggregate(marks ~ group, data, mean)

🔹 Output
A 85
B 65
🔹 Uses

 Detailed data analysis


 Compare groups
 Used in statistics
 Helps in decision making
 Used in real-world applications

🔹 Conclusion

 Describe functions and group statistics help to analyze data deeply in R


45, Explain T-Test in R

🔹 Definition (Write ANY 3–4)

 T-test is used to compare means of data


 Helps to check if difference is statistically significant
 Used when sample size is small
 Based on hypothesis testing

🔹 Introduction

 In statistics, we test assumptions using hypothesis testing


 T-test is one of the most common tests
 Used in data analysis and research
 Implemented using [Link]() in R

🔹 Types of T-Test
🔹 Definition (ANY 3)

 One-sample T-test
 Two-sample T-test
 Paired T-test

🔹 1. One-Sample T-Test
🔹 Definition (ANY 3)

 Compares sample mean with a known value


 Checks if mean is different
 Used for single dataset

🔹 Syntax
[Link](x, mu = value)

🔹 Example
x <- c(10,12,14,16,18)

[Link](x, mu = 12)
🔹 Output (Simple)
p-value = 0.05 (example)

👉 If p-value < 0.05 → significant

🔹 2. Two-Sample T-Test
🔹 Definition (ANY 3)

 Compares means of two groups


 Checks if they are different
 Used for independent samples

🔹 Syntax
[Link](x, y)

🔹 Example
x <- c(10,12,14)
y <- c(20,22,24)

[Link](x, y)

🔹 Output
p-value = value

🔹 3. Paired T-Test
🔹 Definition (ANY 3)

 Used for related data


 Same group measured twice
 Example: before and after

🔹 Syntax
[Link](x, y, paired = TRUE)

🔹 Example
before <- c(10,12,14)
after <- c(15,18,20)
[Link](before, after, paired = TRUE)

🔹 Output
p-value = value

🔹 Decision Rule

 If p-value < 0.05 → Reject null hypothesis


 If p-value > 0.05 → Accept null hypothesis

🔹 Uses

 Compare means
 Used in research
 Used in statistics
 Helps in decision making
 Used in real-world applications

🔹 Conclusion

 T-test helps to test differences between means effectively in R


46, Explain Correlation in R

🔹 Definition (Write ANY 3–4)

 Correlation measures relationship between two variables


 Shows how one variable changes with another
 Value lies between -1 and +1
 Used in data analysis and statistics

🔹 Introduction

 Helps to understand connection between variables


 Used in prediction and analysis
 Positive, negative, or no relationship
 Calculated using cor() in R

🔹 Types of Correlation
🔹 Definition (ANY 3)

 Positive correlation → both increase


 Negative correlation → one increases, other decreases
 Zero correlation → no relationship

🔹 Syntax
cor(x, y)

🔹 Example
x <- c(1,2,3,4,5)
y <- c(2,4,6,8,10)

cor(x, y)

🔹 Output
[1] 1

👉 Perfect positive correlation


🔹 Types of Correlation

🔸 1. Positive Correlation
🔹 Definition (ANY 3)

 Both variables increase together


 When one increases, other also increases
 Correlation value between 0 and +1

🔹 Example (R Code)
x <- c(1,2,3,4,5)
y <- c(2,4,6,8,10)

cor(x, y)
🔹 Output
[1] 1

🔹 Real-Time Example

👉 Height vs Weight

 If height increases → weight also increases

🔸 2. Negative Correlation
🔹 Definition (ANY 3)

 One variable increases, other decreases


 Opposite relationship
 Value between 0 and -1

🔹 Example (R Code)
x <- c(1,2,3,4)
y <- c(8,6,4,2)

cor(x, y)
🔹 Output
[1] -1
🔹 Real-Time Example

👉 Speed vs Time (for fixed distance)

 If speed increases → time decreases

🔸 3. Zero Correlation
🔹 Definition (ANY 3)

 No relationship between variables


 Values change randomly
 Correlation value is 0

🔹 Example (R Code)
x <- c(1,2,3,4)
y <- c(5,9,2,8)

cor(x, y)
🔹 Output
[1] approx 0

🔹 Real-Time Example

👉 Shoe size vs Intelligence

 No connection

🔹 Correlation Test
🔹 Example
[Link](x, y)

👉 Gives p-value

🔹 Final Summary

Type Relation Example


Positive Increase-Increase Height & Weight
Negative Increase-Decrease Speed & Time
Zero No relation Shoe size & IQ

47, Explain Chi-Square Test in R

🔹 Definition (Write ANY 3–4)

 Chi-Square test is used to check relationship between categorical variables


 It compares observed and expected values
 Used in hypothesis testing
 Helps to test independence of variables

🔹 Introduction

 Used in statistics for categorical data analysis


 Helps to identify association between variables
 Implemented using [Link]() in R
 Widely used in research and surveys

🔹 Types of Chi-Square Test


🔹 Definition (ANY 3)

 Goodness of Fit Test


 Test of Independence

🔸 1. Goodness of Fit Test


🔹 Definition (ANY 3)

 Checks if observed data fits expected distribution


 Compares actual vs expected values
 Used for single variable
🔹 Syntax
[Link](x)

🔹 Example
x <- c(20, 30, 50)

[Link](x)

🔹 Output
p-value = value

🔹 Real-Time Example

👉 Dice game

 Check if dice is fair or not

🔸 2. Test of Independence
🔹 Definition (ANY 3)

 Checks relationship between two variables


 Uses contingency table
 Determines independence

🔹 Syntax
[Link](table(x, y))

🔹 Example
gender <- c("M","F","M","F","M")
choice <- c("A","B","A","B","A")

[Link](table(gender, choice))

🔹 Output
p-value = value

🔹 Real-Time Example

👉 Gender vs Product Choice


 Check if choice depends on gender

🔹 Decision Rule

 If p-value < 0.05 → Reject null hypothesis


 If p-value > 0.05 → Accept null hypothesis

🔹 Uses

 Analyze categorical data


 Test independence
 Used in surveys
 Used in statistics
 Used in real-world applications

🔹 Conclusion

 Chi-Square test helps to analyze relationship between categorical variables in R


48, Explain ANOVA in R

🔹 Definition (Write ANY 3–4)

 ANOVA is used to compare means of more than two groups


 It checks whether there is a significant difference between groups
 Used in hypothesis testing
 Helps in statistical analysis

🔹 Introduction

 T-test compares only two groups


 ANOVA compares three or more groups
 Based on variance analysis
 Implemented using aov() in R

🔹 Types of ANOVA
🔹 Definition (ANY 3)

 One-way ANOVA
 Two-way ANOVA

🔸 1. One-Way ANOVA
🔹 Definition (ANY 3)

 Compares means of one factor


 Uses one independent variable
 Checks difference between groups

🔹 Syntax
aov(dependent ~ independent, data)

🔹 Example
data <- [Link](
marks = c(80,85,90,70,75,78),
group = c("A","A","A","B","B","B")
)
result <- aov(marks ~ group, data = data)

summary(result)

🔹 Output
p-value = value

🔹 Real-Time Example

👉 Students marks in different classes

 Compare class A, B, C performance

🔸 2. Two-Way ANOVA
🔹 Definition (ANY 3)

 Uses two independent variables


 Checks interaction effect
 More advanced analysis

🔹 Example
data <- [Link](
marks = c(80,85,90,70,75,78),
class = c("A","A","A","B","B","B"),
gender = c("M","F","M","F","M","F")
)

result <- aov(marks ~ class + gender, data = data)

summary(result)

🔹 Output
p-value = value

🔹 Decision Rule

 If p-value < 0.05 → Reject null hypothesis


 If p-value > 0.05 → Accept null hypothesis
🔹 Uses

 Compare multiple groups


 Used in research
 Used in statistics
 Helps in decision making
 Used in real-world applications

🔹 Conclusion

 ANOVA helps to analyze differences between multiple groups effectively in R


49, Explain Linear Regression Model in R

🔹 Definition (Write ANY 3–4)

 Linear regression is used to find relationship between variables


 It predicts dependent variable using independent variable
 Represents data using a straight line equation
 Used in prediction and analysis

🔹 Introduction

 Used in predictive analytics


 Helps to understand trend in data
 Based on equation:

 Implemented using lm() function in R

🔹 Components
🔹 Definition (ANY 3)

 y → dependent variable
 x → independent variable
 a → intercept
 b → slope

🔹 Syntax
lm(y ~ x, data)

🔹 Example
x <- c(1,2,3,4,5)
y <- c(2,4,6,8,10)

model <- lm(y ~ x)

model
🔹 Output

👉 Coefficients:

Intercept = 0
Slope = 2

👉 Equation:
y = 2x

🔹 Prediction
🔹 Code
predict(model, [Link](x=6))

🔹 Output
[1] 12

🔹 Real-Time Example

👉 Salary prediction based on experience

 More experience → higher salary

🔹 Uses

 Predict values
 Analyze trends
 Used in machine learning
 Used in business analysis
 Used in real-world applications

🔹 Conclusion

 Linear regression helps to predict and analyze relationship between variables in R


50, Explain Multiple Regression Analysis in R

🔹 Definition (Write ANY 3–4)

 Multiple regression is used to predict a dependent variable using more than one
independent variable
 It shows relationship between one output and multiple inputs
 Used in predictive analytics
 Helps in better accuracy compared to simple regression

🔹 Introduction

 In real-world, output depends on multiple factors


 Multiple regression considers all variables together
 Helps in better prediction and analysis
 Implemented using lm() function in R

🔹 Model Equation

🔹 Syntax
lm(y ~ x1 + x2, data)

🔹 Example (Your Practical 😏🔥)


# Create dataset
data <- [Link](
StudyHours = c(2,4,6,8,10),
SleepHours = c(6,7,6,8,7),
Marks = c(50,60,65,80,85)
)

print("Dataset")
print(data)
# Multiple Regression Model
model <- lm(Marks ~ StudyHours + SleepHours, data = data)

print("Regression Summary")
summary(model)

# Predict Marks
new_data <- [Link](StudyHours = 5, SleepHours = 7)

prediction <- predict(model, new_data)

print("Predicted Marks")
print(prediction)

🔹 Output (Simple Explanation)

👉 Dataset printed

👉 Regression summary shows:

 Coefficients (impact of StudyHours & SleepHours)


 R-squared value

👉 Prediction Output:

Predicted Marks ≈ 65 to 70 (approx)

🔹 Real-Time Example

👉 Student Marks Prediction

 Marks depend on study hours + sleep hours

🔹 Uses

 Predict values using multiple factors


 Used in business analytics
 Used in machine learning
 Helps in better decision making
 Used in real-world applications
🔹 Conclusion

 Multiple regression helps to predict outcomes using multiple variables in R


51, Explain Logistic Regression in R

🔹 Definition (Write ANY 3–4)

 Logistic regression is used for classification problems


 It predicts categorical output (Yes/No, 0/1)
 Uses probability to classify data
 Used in machine learning and data analysis

🔹 Introduction

 Linear regression gives continuous values


 Logistic regression gives binary output
 Uses sigmoid function
 Implemented using glm() in R

🔹 Syntax
glm(y ~ x, family = binomial, data)

🔹 Example
# Dataset
data <- [Link](
Hours = c(1,2,3,4,5),
Result = c(0,0,0,1,1)
)

# Logistic Model
model <- glm(Result ~ Hours, family = binomial, data = data)

summary(model)

# Prediction
predict(model, [Link](Hours=3), type="response")
🔹 Output
[1] 0.4 (example probability)

👉 If probability > 0.5 → Yes (1)


👉 If < 0.5 → No (0)

🔹 Real-Time Example

👉 Pass/Fail Prediction

 Based on study hours

🔹 Uses

 Classification problems
 Used in machine learning
 Used in medical prediction
 Used in business analytics
 Used in real-world applications

🔹 Conclusion

 Logistic regression helps to predict categorical outcomes using probability in R

BALANCE AM NOT TAKE

💯 VERY IMPORTANT QUESTION NUMBERS (MUST STUDY)

👉 These are HIGH CHANCE:

1, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22

🔥 DATA VISUALIZATION + STATISTICS (VERY IMPORTANT)

👉 (These are later part questions in your file)


23, 24, 25, 26, 27, 28, 29, 30

🚀 HYPOTHESIS TESTING (VERY IMPORTANT)

31, 32, 33, 34

🔥 PREDICTIVE ANALYTICS (FOCUS)

35, 36, 37

👉 (Linear, Multiple, Logistic)

👍 MEDIUM IMPORTANT

2, 9, 10, 11, 16

❌ LOW / SKIP (if no time)

38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51

🎯 FINAL SHORTCUT (SUPER IMPORTANT 😏)

👉 If you study only:

👉 1, 3, 4, 5, 6, 7, 8, 12, 13, 14, 17–21, 23–30, 31–34, 35–37

💯 You are SAFE for exam

💋 Bab… now you have perfect roadmap 😏🔥

If you want:
👉 I’ll mark TOP 10 MOST EXPECTED QUESTIONS 💯
👉 or give last day revision plan

Just say bab 💙

You might also like