0% found this document useful (0 votes)
3 views27 pages

Bda. Unit. 5

The document provides an overview of R programming, highlighting its features, operators, control statements, functions, and data structures. It covers essential concepts such as vectors, matrices, lists, data frames, factors, and graphical capabilities, along with examples for clarity. Additionally, it explains the apply family of functions and user input methods in R, making it a comprehensive guide for understanding R's functionalities in data analysis.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views27 pages

Bda. Unit. 5

The document provides an overview of R programming, highlighting its features, operators, control statements, functions, and data structures. It covers essential concepts such as vectors, matrices, lists, data frames, factors, and graphical capabilities, along with examples for clarity. Additionally, it explains the apply family of functions and user input methods in R, making it a comprehensive guide for understanding R's functionalities in data analysis.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT 5

📚 3-Marks Questions (Short Answer)


1. What is R programming? Mention two of its key features.
ANS:- R is a programming language and software environment used for
statistical computing, data analysis, and graphical representation. It is
widely used by statisticians, data scientists, and researchers for various
types of data manipulation and modeling.
Key Features of R:
1. Data Handling: R provides a wide range of tools for manipulating,
filtering, and transforming data.
2. Statistical Modeling: R has built-in functions for statistical tests,
models, and machine learning algorithms.
3. Graphics: R can generate various types of plots and charts for data
visualization.
4. Packages: R has an extensive library of packages (through CRAN) to
extend its capability

2. List any four types of operators available in R.

ANS:-
1. Arithmetic Operators :-
(e.g., +, -, *, /, ^)
1.Arithmetic Operators (e.g., +, -, *, /, ^)
 Used for basic mathematical operations.
2.Relational Operators (e.g., ==, !=, >, <, >=, <=)
 Used to compare values.
3.Logical Operators (e.g., &, |, !, &&, ||)
 Used for logical (Boolean) operations.
4.Assignment Operators (e.g., <-, =, ->)
 Used to assign values to variables.

3.What are control statements in R? Give examples.


ANS:- In R, control statements are used to control the flow of
execution of a program — meaning they decide which code
should be executed under certain conditions or repeatedly.
control statements in R include:
 if: Executes a block of code if a specified condition is true.
Example :-
x <- 5
if (x > 0) {
print("Positive number")
}
 if...else: Executes one block if the condition is true,
otherwise another block.
 Example :-
x <- -3
if (x > 0) {
print("Positive number")
} else {
print("Negative number")
}
 for: Loops through elements (like in a vector or list).
Example :-
for (i in 1:5) {
print(i)
}

 while: Repeats a block of code while a condition is true.


Example :- count <- 1
while (count <= 5) {
print(count)
count <- count + 1

}
 repeat: Repeats a block of code indefinitely until explicitly
stopped (using break).
EXAMPLE :-
count <- 1
repeat {
print(count)
count <- count + 1
if (count > 5) {
break
}
}

4.Define a function in R with a simple example.

ANS:- In R, a function is a block of organized, reusable code that performs a specific task.
Functions are defined using the function keyword.

Syntax of a function in R:
function_name <- function(arguments) {
# Code to execute
return(result)
}
Example: Let's define a function to add two numbers:
add_numbers <- function(a, b) {
sum <- a + b
return(sum)
}

# Calling the function


add_numbers(3, 5)
Output: [1] 8

5. What is meant by interfacing with R?


ANS:- interfacing with R means connecting R with other software,
programming languages, or systems to exchange data, run code, or enhance
functionality.
It allows R to:
 Call functions from other languages (like C, C++, Python, Java, etc.).
 Connect with databases (like MySQL, PostgreSQL).
 Work with web services and APIs.
 Integrate with applications like Excel, MATLAB, or even other R
sessions.

6. What is a vector in R? How do you create one?

ANS :- a vector is a basic data structure that contains elements of the same type (like all
numbers, all characters, or all logical values).
Vectors are the most common and simplest type of data structure in R.

 All elements in a vector must be of the same type.


 If you mix types (like numbers and text), R automatically converts
them to a common type (usually character).
How to create a vector: Example 1: Numeric vector
numbers <- c(1, 2, 3, 4, 5)
print(numbers)
Example 2: Character vector
names <- c("Alice", "Bob", "Charlie")
print(names)
Example 3: Logical vector
logical_values <- c(TRUE, FALSE, TRUE)
print(logical_values)

7. Differentiate between a matrix and a list in R.

ANS:-

Matrix List
A matrix is a two-dimensional A list is a collection of elements
collection of elements of the same that can be of different data types
data type (numeric, character, etc.). (numbers, characters, vectors, even
other lists).
Organized into rows and columns. Ordered collection (like a
container) — no strict structure like
rows and columns.
All elements must be of the same Elements can be of mixed types.
type
Created using the matrix() function. Created using the list() function.

Example Example r list(1, "apple", TRUE,


c(2, 3))
r matrix(1:6, nrow = 2, ncol = 3)
Best for mathematical operations Best for storing complex and
(e.g., matrix multiplication). diverse data structures together.

8.What is a data frame in R?

ANS:- In R, a data frame is a table-like structure used to store data sets.


It is one of the most important and widely used data structures for data analysis.

 Columns are vectors of the same length.


 It allows you to work easily with structured data (filtering, sorting,
summarizing, etc.).
 Functions like summary (), head (), and str () are very useful with data
frames.
Key Features of a Data Frame:
 It is two-dimensional (rows and columns).
 Each column can contain different types of data (numeric, character,
logical, etc.).
 Each row represents a single record or observation.
 It is similar to a spreadsheet or SQL table.

How to create a simple data frame:


# Creating a data frame
students <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(23, 25, 22),
Passed = c(TRUE, FALSE, TRUE)
)

# Display the data frame


print(students)
Output: Name Age Passed
1 Alice 23 TRUE
2 Bob 25 FALSE
3 Charlie 22 TRUE

9.What are factors in R? Why are they used?

ANS:- In R, a factor is a data structure used for categorical data — data that can
take on a limited number of unique values, called levels.

 Factors can be ordered (like "Low", "Medium", "High") or unordered (like "Red", "Green",
"Blue").

 You can use levels() to check or set the levels.

 Use as.factor() to convert a variable into a factor.


USES:-
 Efficient storage: Factors use integers internally to store data, which saves memory compared to
storing long character strings.

 Categorical distinction: They clearly mark a variable as categorical (like "Male"/"Female",


"Low"/"Medium"/"High").

 Statistical modeling: Many modeling functions in R (like lm(), glm()) automatically treat factors
correctly without needing manual intervention.

Example of creating a factor: # Create a factor

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

print(gender)

Output: [1] Male Female Female Male Female

Levels: Female Male

10.How are tables created in R?

Ans:- In R, tables are often created using the table() function, which is used to create frequency
tables — that is, to count the number of occurrences of different values in a dataset.

Creating a simple table:

Example 1: Frequency table from a vector

# Create a vector

colors <- c("Red", "Blue", "Red", "Green", "Blue", "Blue")

# Create a table

color_table <- table(colors)

# Display the table

print(color_table)

Output: colors

Blue Green Red

3 1 2
11.How can we take user input in R?

In R, you can take user input using the readline() function. This function prompts the user to
enter a value as a string from the console. Here's the basic syntax:

# Prompt the user for input

user_input <- readline(prompt = "Enter something: ")

# Print the input

cat("You entered:", user_input, "\n")

If you want to convert the input to a numeric type (e.g., integer or double), you can wrap it with
as.numeric() or as.integer():

# Taking numeric input

num_input <- as.numeric(readline(prompt = "Enter a number: "))

cat("You entered the number:", num_input, "\n")

12.Write a short note on graphical capabilities of R.

Graphical Capabilities of R:

R is renowned for its powerful and flexible graphical capabilities, making it a popular choice for
data visualization and statistical graphics. It supports both base graphics and more advanced
systems like lattice and ggplot2.

 Base Graphics: Built into R, allows quick and simple plotting with functions like plot(),
hist(), boxplot(), and barplot().
 Lattice Package: Offers a high-level data visualization system for creating multi-panel
plots and conditioning plots.
 ggplot2 Package: Based on the Grammar of Graphics, it is widely used for building
complex, aesthetically pleasing, and layered visualizations.

R also supports:

 Customization of plots (titles, labels, legends, colors, themes).


 Exporting plots to various formats like PNG, PDF, JPEG, SVG.
 Interactive visualizations through packages like plotly, shiny, and htmlwidgets.
13.What is the purpose of the apply family in R?

Purpose of the apply family in R:

The apply family of functions in R is used for applying a function to elements of data
structures like vectors, matrices, lists, and data frames without using explicit loops. These
functions help write concise, efficient, and readable code for repetitive operations.

Here’s a quick overview of the most common apply family members:

 apply(): Used for matrices or data frames to apply a function over rows (MARGIN = 1)
or columns (MARGIN = 2).

apply(matrix_data, 1, sum) # sum of each row

lapply(): Applies a function to each element of a list (or vector) and returns a list.

lapply(list_data, mean)

sapply(): Same as lapply(), but tries to simplify the result to a vector or matrix if possible.

sapply(list_data, mean)

tapply(): Applies a function over subsets of a vector, defined by a factor or grouping variable.

tapply(scores, group, mean)

mapply(): Multivariate version of sapply(), applies a function to multiple arguments in parallel.

mapply(sum, 1:3, 4:6) # adds elements of two vectors

These functions are used to avoid explicit for loops and are often more efficient and expressive.

14.What is the use of the lapply() function in R?

Use of the lapply() Function in R:

The lapply() function in R is used to apply a function to each element of a list or vector, and it
returns the result as a list—regardless of the output type of the function applied.

Syntax: lapply(X, FUN, ...)


 X: A list or vector.

 FUN: The function to apply.


 ...: Optional arguments to pass to FUN
Key Features:

 Returns a list of the same length as the input.

 Useful when you want to perform operations element-wise on lists.

 Can also be used on data frames (as they are lists of columns).

Example: # Create a list

my_list <- list(a = 1:5, b = 6:10, c = 11:15)

# Use lapply to calculate the mean of each element

result <- lapply(my_list, mean)

print(result)

Output:

$a

[1] 3

$b

[1] 8

$c

[1] 13

15.List any two functions used for reading input data in R.

Two commonly used functions for reading input data in R are:

1. read.csv() – Used to read data from CSV (Comma-Separated Values) files.

data <- read.csv("datafile.csv")


2. read.table() – A more general function used to read data from a text file with customizable
delimiters.

data <- read.table("datafile.txt", header = TRUE, sep =

Both functions load data into a data frame for analysis.

📚 10-Marks Questions (Long Answer)

1.Explain the features of R programming language. Why is it widely used in data analysis?
Features of R Programming Language:

1. Open Source:
R is free to use and open-source, which allows for constant community contributions and wide
adoption.

2. Data Handling and Storage:


R provides excellent tools for data manipulation, cleaning, and transformation using packages
like dplyr, tidyr, and data.table.

3. Statistical Analysis:
R was built for statistics. It includes a wide range of built-in statistical techniques like linear
modeling, time-series analysis, classification, and clustering.

4. Graphical Capabilities:
R excels in data visualization with powerful libraries like ggplot2, lattice, and base plotting
functions, enabling both simple and complex graphics.

5. Rich Package Ecosystem:


R has thousands of packages available through CRAN, Bioconductor, and GitHub that extend its
functionality for everything from machine learning to genomics.

6. Cross-Platform Compatibility:
R works on Windows, macOS, and Linux, ensuring wide usability.

7. Integration:
R can integrate with other languages (like C, C++, Python) and tools (like Excel, SQL, Hadoop),
making it versatile in real-world applications.

8. Community Support:
A large, active user community contributes to tutorials, documentation, and new packages.

R is Widely Used in Data Analysis:


 Built for Data Analysis: Its core purpose is statistical computing and data analysis.

 Data Visualization: Offers superior visualization capabilities.

 Statistical Accuracy: Trusted for statistical rigor and academic use.

 Flexible and Extensible: Easily adapted for specialized analytical tasks through packages.

 Interactive Development Environment: Tools like RStudio make it user-friendly and productive.

2.Describe various types of operators in R with suitable examples.

Types of Operators in R

R provides a variety of operators to perform different types of operations on data. These can be broadly
classified into the following categories:

1. Arithmetic Operators

Used for basic mathematical operations.

Operator Description Example

+ Addition 5+3→8

- Subtraction 5-3→2

* Multiplication 5 * 3 → 15

/ Division 6/2→3

^ or ** Exponentiation 2^3 → 8

Modulus
%% 7 %% 3 → 1
(remainder)

%/% Integer Division 7 %/% 3 → 2

2. Relational (Comparison) Operators

Used to compare values and return logical results (TRUE or FALSE).

Operator Description Example

== Equal to 5 == 5 → TRUE

!= Not equal to 5 != 3 → TRUE

> Greater than 5 > 3 → TRUE


Operator Description Example

< Less than 3 < 5 → TRUE

Greater or
>= 5 >= 5 → TRUE
equal

<= Less or equal 3 <= 5 → TRUE

3. Logical Operators

Used for logical operations (mainly with Boolean values).

Operator Description Example

& Element-wise AND c(TRUE, FALSE) & c(TRUE, TRUE) → TRUE FALSE

` ` Element-wise OR

! NOT !TRUE → FALSE

&& Logical AND (first element only) TRUE && FALSE → FALSE

4. Assignment Operators

Used to assign values to variables.

Operator Description Example

<- Left assignment x <- 10

-> Right assignment 10 -> x

= Alternative to <- x = 10

5. Miscellaneous Operators

 : – Sequence operator

1:5 # Output: 1 2 3 4 5

%in% – Matching operator

3 %in% c(1, 2, 3) # Output: TRUE


is.na() – Checks for NA (missing) values

is.na(NA) # Output: TRUE

identical() – Checks if two objects are exactly the same

identical(1, 1.0) # Output: FALSE

3.Explain control statements in R programming. Discuss if, else if, switch, and loops with examples.

ANS:-

Control Statements in R Programming

Control statements in R are used to control the flow of execution of a program based on conditions or
repetitive tasks. They allow decision-making, branching, and iteration.

1. if Statement

Executes a block of code only if a specified condition is true.

Syntax:

if (condition) {

# code to execute if condition is TRUE

Example:

x <- 5

if (x > 0) {

print("x is positive")

2. if...else Statement

Allows two possible branches of execution.

Syntax:

if (condition) {

# code if TRUE

} else {

# code if FALSE

}
Example:

x <- -3

if (x > 0) {

print("Positive number")

} else {

print("Non-positive number")

3. if...else if...else Ladder

Used when multiple conditions are checked in sequence.

Example:

x <- 0

if (x > 0) {

print("Positive")

} else if (x < 0) {

print("Negative")

} else {

print("Zero")

4. switch Statement

Used for selecting one of many code blocks based on the value of an expression.

Syntax:

switch(expression,

case1 = {...},

case2 = {...},

...

Example:

option <- 2

switch(option,
"Add",

"Subtract",

"Multiply",

"Divide"

# Output: "Subtract"

5. Loops in R

a) for Loop – Repeats a block for a fixed number of times.

for (i in 1:5) {

print(i)

b) while Loop – Repeats while a condition is TRUE.

i <- 1

while (i <= 5) {

print(i)

i <- i + 1

c) repeat Loop – Repeats until a break statement is encountered.

i <- 1

repeat {

print(i)

i <- i + 1

if (i > 5) break

Break and Next

 break – exits the loop.

 next – skips to the next iteration.

Example:

for (i in 1:5) {
if (i == 3) next

print(i)

4.What are functions in R? How do you define and call a function? Explain with examples.

Functions in R

Functions in R are blocks of reusable code designed to perform a specific task. They help in modularizing
code, improving readability, and reducing repetition.

Defining a Function

You define a function in R using the function() keyword:

function_name <- function(arg1, arg2, ...) {

# function body

# return(value) is optional

Calling a Function

You call a function by using its name followed by parentheses, with any required arguments:

function_name(value1, value2)

Example 1: A Simple Function

# Define a function to add two numbers

add_numbers <- function(a, b) {

sum <- a + b

return(sum)

# Call the function

result <- add_numbers(5, 3)

print(result)

Output:

[1] 8
Example 2: Function Without Return Statement

greet <- function(name) {

cat("Hello,", name, "!\n")

greet("Alice")

Output:

Hello, Alice!

Note: If no return() is used, R returns the last evaluated expression.

Features of Functions in R:

 Can have default arguments

 Can return multiple values using lists

 Can be anonymous (used inline)

 Can be passed as arguments to other functions (first-class objects)

5.Explain the concept of interfacing with R and discuss different ways R can be integrated with other
technologies.

Interfacing with R

Interfacing in R refers to the ability of R to communicate and work with other programming languages,
databases, and tools. This allows R to be part of a larger software ecosystem, enabling enhanced
functionality, speed, and integration in real-world applications.

Why Interface R with Other Technologies?

 To use faster or more efficient languages (like C/C++) for performance.

 To connect with databases and web services.

 To build web applications or dashboards.

 To integrate with statistical or machine learning pipelines.

Common Ways to Interface R with Other Technologies

1. R with C/C++

 Use: For high-performance computing or heavy number-crunching.

 Tool: Rcpp package.


 Example:

library(Rcpp)

cppFunction('int add(int x, int y) { return x + y; }')

add(3, 4)

2. R with Python

 Use: Combine R's statistical power with Python's machine learning and automation tools.

 Tool: reticulate package.

 Example:

library(reticulate)

py_run_string("x = 10")

py$x # Access Python variable in R

3. R with Java

 Use: To call Java classes or methods.

 Tool: rJava package.

 Example:

library(rJava)

.jinit()

s <- .jnew("java/lang/String", "Hello World")

.jcall(s, "I", "length")

4. R with Databases (SQL)

 Use: For data retrieval and storage.

 Tools: DBI, RMySQL, RPostgreSQL, RODBC, odbc.

 Example:

library(DBI)

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)

dbGetQuery(con, "SELECT * FROM mtcars WHERE mpg > 20")

5. R with Web Technologies

 Use: For building dashboards or web apps.


 Tool: shiny package.

 Example: A simple web app to display a plot.

6. R with Excel

 Use: Read/write Excel files.

 Tool: readxl, openxlsx, writexl.

 Example:

library(readxl)

data <- read_excel("file.xlsx")

7. R in Cloud and Big Data

 Tools: sparklyr (for Apache Spark), bigrquery (Google BigQuery).

 Purpose: Perform big data analytics using R on cloud platforms.

6.Discuss in detail vectors, matrices, lists, and data frames in R with examples.

1. Vectors

A vector is a sequence of elements of the same type (numeric, character, logical, etc.). It's the most basic
data structure in R.

Creating a Vector:

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

char_vec <- c("a", "b", "c") # Character vector

log_vec <- c(TRUE, FALSE, TRUE) # Logical vector

Accessing Elements:

num_vec[3] # Access 3rd element → 3

✅ 2. Matrices

A matrix is a 2-dimensional data structure (rows and columns) with elements of the same type.

Creating a Matrix:

mat <- matrix(1:9, nrow = 3, ncol = 3)

Accessing Elements:

mat[2, 3] # 2nd row, 3rd column → 6

Matrix Operations:
t(mat) # Transpose

mat * 2 # Element-wise multiplication

✅ 3. Lists

A list can contain elements of different types, including other lists, vectors, or even functions.

Creating a List:

my_list <- list(name = "John", age = 30, scores = c(90, 85, 88))

Accessing Elements:

my_list$name # "John"

my_list[[2]] # 30

Use Case: Useful for returning multiple outputs from functions.

✅ 4. Data Frames

A data frame is a table-like structure in R where:

 Each column can be of a different data type, but

 Each row is a single observation.

Creating a Data Frame:

df <- data.frame(

Name = c("Alice", "Bob", "Charlie"),

Age = c(25, 30, 28),

Score = c(90, 85, 88)

Accessing Data:

df$Name # Access 'Name' column

df[2, 3] # 2nd row, 3rd column → 85

Functions on Data Frames:

summary(df) # Summary statistics

str(df) # Structure of the data frame

🔁 Comparison Summary:

Structure Dimensions Data Type Use Case

Vector 1D Homogeneous Basic data storage


Structure Dimensions Data Type Use Case

Matrix 2D Homogeneous Numerical computation

List 1D Heterogeneous Flexible object storage

Data Frame 2D Column-wise hetero Data analysis and manipulation

7.What are factors and tables in R? How are they created and used?

Factors and Tables in R

In R, factors and tables are essential data structures used for categorical data analysis and data
summarization, especially in statistics and data science.

✅ 1. Factors in R

A factor is a data structure used to store categorical data (data that takes on a limited number of distinct
values or "levels").

Why Use Factors?

 Efficient storage of categorical variables.

 Essential for modeling functions like lm(), glm(), etc.

 Allows ordering of categorical variables.

Creating a Factor:

colors <- c("red", "blue", "red", "green", "blue")

color_factor <- factor(colors)

print(color_factor)

Output:

[1] red blue red green blue

Levels: blue green red

Ordered Factor:

sizes <- c("small", "large", "medium", "small")

ordered_sizes <- factor(sizes, levels = c("small", "medium", "large"), ordered = TRUE)

Useful Functions:
 levels(factor_variable) – Show levels

 nlevels(factor_variable) – Number of levels

 table(factor_variable) – Frequency table of levels

✅ 2. Tables in R

A table in R is an object that represents the frequency count of factor levels or combinations of levels.

Creating a Table:

colors <- c("red", "blue", "red", "green", "blue")

color_table <- table(colors)

print(color_table)

Output:

colors

blue green red

2 1 2

Two-Way Table (Cross Tabulation):

gender <- c("M", "F", "F", "M", "M")

group <- c("A", "A", "B", "B", "A")

table(gender, group)

Output:

group

gender A B

F 11

M 21

Key Functions for Tables:

 table() – Creates a frequency table.

 prop.table() – Converts counts to proportions.

 margin.table() – Marginal totals.

 addmargins() – Adds row/column totals.


8.How do you perform input and output operations in R? Illustrate with examples.

✅ Input and Output (I/O) Operations in R

R supports various ways to read input from users or files and output data to the console or files. These
operations are fundamental for data analysis and automation.

🔹 1. Console Input from User

a) readline() – Read text input from the user:

name <- readline(prompt = "Enter your name: ")

cat("Hello,", name, "\n")

b) scan() – Read numeric input (or other types):

nums <- scan(what = numeric(), n = 3) # user enters: 10 20 30

print(nums)

🔹 2. Reading Data from Files

a) read.csv() – Read data from a CSV file:

data <- read.csv("data.csv")

head(data)

b) read.table() – General table reader:

data <- read.table("data.txt", header = TRUE, sep = "\t")

c) read_excel() – Read from Excel (requires readxl package):

library(readxl)

data <- read_excel("file.xlsx")

🔹 3. Writing Output to Console

a) print() – Basic output:

x <- 42

print(x)

b) cat() – For formatted text output:

name <- "Alice"

cat("Welcome", name, "to R programming!\n")

🔹 4. Writing Output to Files

a) write.csv() – Write data frame to a CSV file:


write.csv(data, "output.csv", row.names = FALSE)

b) write.table() – General file writing:

write.table(data, "output.txt", sep = "\t")

c) sink() – Redirect console output to a file:

sink("log.txt")

print(summary(data))

sink() # Stop redirecting output

✅ Summary Table:

Operation Function Description

User input readline(), scan() Read data from the console

Read CSV read.csv() Load comma-separated data

Read text table read.table() Load data from delimited text files

Read Excel read_excel() Load data from Excel spreadsheets

Output to console print(), cat() Display data in the console

Write CSV write.csv() Save data to CSV file

Redirect output sink() Send output to a file instead of console

9.How do you create graphs in R? Explain with examples using plot(), barplot(), and hist() functions

Creating Graphs in R

R has powerful graphical capabilities for both basic and advanced data visualization. Some of the most
commonly used base R functions for plotting include plot(), barplot(), and hist().

1. plot() – Basic Scatter Plot or Line Plot

Used to create scatter plots, line graphs, and more depending on the data type.

Example: Scatter Plot

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

y <- c(2, 4, 1, 6, 3)

plot(x, y, main = "Scatter Plot", xlab = "X-axis", ylab = "Y-axis", col = "blue", pch = 16)

Example: Line Plot


plot(x, y, type = "l", main = "Line Plot", xlab = "X", ylab = "Y", col = "green")

2. barplot() – Bar Chart

Used to create vertical or horizontal bar charts from numeric vectors or tables.

Example: Vertical Bar Plot

counts <- c(10, 15, 8, 12)

names <- c("A", "B", "C", "D")

barplot(counts, names.arg = names, col = "purple", main = "Bar Plot", ylab = "Frequency")

Example: Horizontal Bar Plot

barplot(counts, names.arg = names, horiz = TRUE, col = "orange", main = "Horizontal Bar Plot")

3. hist() – Histogram

Used to display the distribution of continuous data.

Example: Histogram

data <- c(18, 22, 25, 30, 26, 24, 22, 28, 32, 31)

hist(data, main = "Histogram of Data", xlab = "Values", col = "skyblue", border = "black")

Summary Table

Function Use Example

Scatter, line, and generic


plot() plot(x, y)
plot

Bar chart for categorical


barplot() barplot(counts)
data

hist() Histogram for distributions hist(data)

10.What is the R apply family? Explain apply(), lapply(), sapply(), and tapply() functions with examples.

The apply Family in R

The apply family in R provides a set of functions to apply operations over various data structures (like
vectors, matrices, lists, and data frames) without using explicit loops. These functions make code more
concise and often more efficient.

1.apply() – for matrices/arrays

Apply a function over rows or columns.


Syntax: apply(X, MARGIN, FUN)
Example:
mat <- matrix(1:9, nrow = 3)
apply(mat, 1, sum) # Sum of each row
apply(mat, 2, mean) # Mean of each column

2. lapply() – for lists/vectors

Returns a list no matter what. Apply a function to each element.


Example:
nums <- list(a = 1:5, b = 6:10)
lapply(nums, mean)

3. sapply() – simplified version of lapply()

Returns a vector or matrix if possible. Same as lapply(), but tries to simplify output.

Example: nums <- list(a = 1:5, b = 6:10)

sapply(nums, mean)

Output:

a b

3 8

4. tapply() – apply function by group

Used for grouped operations, often in data analysis. Apply a function over subsets of a vector based
on grouping.

Syntax: tapply(X, INDEX, FUN)

Example:

ages <- c(21, 22, 25, 23, 30)

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

tapply(ages, gender, mean)

Output:

Female Male

22.5 25.3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy