0% found this document useful (0 votes)
4 views28 pages

Unit-5 (R-Programming)

R is an open-source programming language designed for statistical computing and data analysis, widely used in various fields such as data science and finance. It offers comprehensive statistical tools, exceptional data visualization capabilities, and a strong community support, making it an essential tool for data-related tasks. The document also covers R's operators, control statements, and provides guidance on getting started with R programming.
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)
4 views28 pages

Unit-5 (R-Programming)

R is an open-source programming language designed for statistical computing and data analysis, widely used in various fields such as data science and finance. It offers comprehensive statistical tools, exceptional data visualization capabilities, and a strong community support, making it an essential tool for data-related tasks. The document also covers R's operators, control statements, and provides guidance on getting started with R programming.
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

R-Programming

R is a powerful and widely used open-source programming language and software


environment specifically designed for statistical computing, data analysis, and graphical
display. It has become a cornerstone in various fields, including data science, academic
research, finance, and healthcare, due to its robust capabilities and extensive ecosystem.

1. What is R?

● Statistical Computing and Graphics: R's primary strength lies in its comprehensive
suite of tools for statistical analysis, modeling, and creating high-quality data
visualizations.
● Open-Source and Free: R is freely available for anyone to use, modify, and
distribute. This fosters a vibrant community and a wealth of shared resources.
● Interpreted Language: Unlike compiled languages, R executes code line by line
through a command-line interpreter, allowing for interactive data exploration and
immediate feedback.
● Domain-Specific Language (DSL): While not a general-purpose language like
Python or Java, R is highly specialized for data-related tasks, making it incredibly
efficient for its intended domain.
● High-Level Language: R is designed to be easily understood and written by humans,
abstracting away complex computer memory and processes.

2. Key Features and Strengths:

● Comprehensive Statistical Tools: R boasts a vast collection of built-in functions and


packages for a wide range of statistical analyses, including regression, time-series
analysis, clustering, hypothesis testing, and more.
● Exceptional Data Visualization: With powerful packages like ggplot2, R allows
users to create highly customizable, informative, and interactive charts and plots for
effective data presentation.
● Data Wrangling and Manipulation: R provides excellent tools (e.g., dplyr, tidyr)
for importing, cleaning, transforming, and preparing data from various sources,
making it ready for analysis.
● Reproducible Research: R, especially when combined with tools like R Markdown,
facilitates reproducible research by allowing users to integrate code, output, and
narrative in a single document.
● Extensive Package Ecosystem (CRAN): The Comprehensive R Archive Network
(CRAN) hosts thousands of user-contributed packages that extend R's functionality
for virtually any data-related task, from machine learning to bioinformatics.
● Cross-Platform Compatibility: R runs seamlessly on various operating systems,
including Windows, macOS, and Linux.
● Strong Community Support: R has a large and active global community, offering
abundant online resources, forums, tutorials, and support for users of all levels.
3. Common Use Cases:

● Data Analysis and Statistics: R is the go-to language for statisticians and data
analysts for performing in-depth statistical analysis, hypothesis testing, and exploring
data patterns.
● Data Visualization: Creating compelling and insightful graphs, charts, and
dashboards is a core application of R.
● Machine Learning and Data Science: R is widely used for building predictive
models, implementing machine learning algorithms, and conducting data science
projects.
● Financial Analysis: In finance, R is used for quantitative modeling, risk analysis, and
portfolio management.
● Healthcare and Bioinformatics: R plays a crucial role in analyzing medical data,
conducting clinical research, and performing genomic analysis.
● Academic Research: Researchers across disciplines rely on R for data analysis and
publishing reproducible results.

4. Getting Started with R:

● Install R: Download and install the R base system from the official CRAN website.
● Choose an IDE (Integrated Development Environment): While R comes with a
command-line interface, using an IDE like RStudio is highly recommended. RStudio
provides a user-friendly environment with features like syntax highlighting, code
completion, and integrated help.
● Learn Basic Syntax: Familiarize yourself with R's fundamental concepts, including
data types (vectors, lists, data frames), operators, control flow (loops, conditionals),
and functions.
● Explore Packages: Start using popular packages like dplyr for data manipulation and
ggplot2 for data visualization to leverage R's true power.

In essence, R is an indispensable tool for anyone working with data, offering a powerful and
flexible environment for statistical computing, analysis, and visualization. Its open-source
nature, extensive community, and rich ecosystem of packages make it a continuous evolving
and highly valuable asset in the world of data science.

Operators:
In R programming, operators are special symbols or keywords that perform specific
operations on values and variables. Understanding them is fundamental to writing any R
code, as they allow you to manipulate data, perform calculations, make comparisons, and
control program flow.

Here's a breakdown of the main types of operators in R:

1. Arithmetic Operators

These are used for performing mathematical calculations.

Operat Description Example Resu


or lt
+ Addition 5+3 8
- Subtraction 10 - 5 5
* Multiplication 3*5 15
/ Division 10 / 2 5
Modulo
%% 10 %% 4 2
(remainder)
%/% Integer Division 11 %/% 3 3
2 ^ 3 or 2 **
^ or ** Exponentiation 8
3
Export to Sheets

Example:

R
x <- 10
y <- 3

print(x + y) # Output: 13
print(x - y) # Output: 7
print(x * y) # Output: 30
print(x / y) # Output: 3.333333
print(x %% y) # Output: 1 (remainder of 10 / 3)
print(x %/% y) # Output: 3 (integer part of 10 / 3)
print(2^4) # Output: 16

2. Relational (Comparison) Operators

These operators are used to compare two values and return a logical (TRUE or FALSE)
result.

Operat Examp Resul


Description
or le t
FALS
== Equal to 5 == 3
E
TRU
!= Not equal to 5 != 3
E
FALS
< Less than 5<3
E
TRU
> Greater than 5>3
E
FALS
<= Less than or equal to 5 <= 3
E
Greater than or equal TRU
>= 5 >= 3
to E
Export to Sheets

Example:

R
a <- 7
b <- 5

print(a == b) # Output: FALSE


print(a != b) # Output: TRUE
print(a < b) # Output: FALSE
print(a > b) # Output: TRUE
print(a <= b) # Output: FALSE
print(a >= b) # Output: TRUE

Important Note on == vs =: In R, == is used for comparison (checking for equality), while


= can also be used for assignment (though <- is generally preferred for assignment to avoid
confusion). Always use == for comparisons.

3. Logical Operators

These operators combine or negate logical values (TRUE or FALSE). They are often used
with relational operators to create more complex conditions.

Operat Resul
Description Example
or t
FALS
& Element-wise Logical AND TRUE & FALSE
E
Logical AND (evaluates only the FALS
&& TRUE && FALSE
first element) E
`TRU
` ` Element-wise Logical OR
E
Logical OR (evaluates only the `TRU
` `
first element) E
FALS
! Logical NOT !TRUE
E
Export to Sheets

Differences between &/| and &&/||:

● & (element-wise AND) and | (element-wise OR): These operators perform element-
wise comparisons when applied to vectors. They return a logical vector of the same
length as the input.
● && (logical AND) and || (logical OR): These operators are typically used in control
flow statements (like if statements). They only evaluate the first element of each
vector and return a single TRUE or FALSE value. This is a "short-circuiting"
evaluation.

Example:

R
x <- c(TRUE, FALSE, TRUE)
y <- c(TRUE, TRUE, FALSE)

print(x & y) # Output: TRUE FALSE FALSE (element-wise AND)


print(x | y) # Output: TRUE TRUE TRUE (element-wise OR)
print(!x) # Output: FALSE TRUE FALSE (element-wise NOT)

if (x[1] && y[1]) {


print("Both first elements are TRUE") # Output: "Both first elements are TRUE"
}

if (x[2] || y[2]) {
print("At least one of the first elements is TRUE") # Output: "At least one of the first
elements is TRUE"
}

4. Assignment Operators

These operators are used to assign values to variables (objects) in R.

Operat
Description Example
or
<- Leftward Assignment (preferred) my_var <- 10
= Assignment (also works, but often used for function arguments) my_var = 10
-> Rightward Assignment 10 -> my_var
Global Assignment (for modifying variables in parent global_var
<<-
environments within functions) <<- 20
20 ->>
->> Global Rightward Assignment
global_var
Export to Sheets

Example:

R
# Preferred assignment
my_number <- 15
print(my_number) # Output: 15

# Also works for assignment, common in function arguments


another_number = 25
print(another_number) # Output: 25

# Rightward assignment
30 -> third_number
print(third_number) # Output: 30

# Global assignment (primarily used within functions to affect variables outside their local
scope)
# Example:
# my_function <- function() {
# global_variable <<- 100
#}
# my_function()
# print(global_variable) # Output: 100
5. Miscellaneous Operators

R has some special operators for specific purposes.

Operat
Description Example Result
or
: Sequence Operator 1:5 [1] 1 2 3 4 5
Membership Operator (checks if an
%in% 3 %in% c(1, 2, 3, 4) TRUE
element is present in a vector)
(Resulting
%*% Matrix Multiplication matrix1 %*% matrix2
matrix)
Component Extraction (for lists, my_dataframe$column_na (Column
$
data frames) me data)
Indexing (for vectors, lists, data (Second
[] my_vector[2]
frames, matrices) element)
Export to Sheets

Example:

R
# Sequence operator
numbers <- 1:5
print(numbers) # Output: [1] 1 2 3 4 5

# Membership operator
fruits <- c("apple", "banana", "cherry")
print("banana" %in% fruits) # Output: TRUE
print("grape" %in% fruits) # Output: FALSE

# Matrix multiplication (requires matrices)


mat1 <- matrix(c(1, 2, 3, 4), nrow = 2)
mat2 <- matrix(c(5, 6, 7, 8), nrow = 2)
print(mat1 %*% mat2)

# Component extraction for data frames


df <- [Link](Name = c("Alice", "Bob"), Age = c(25, 30))
print(df$Age) # Output: [1] 25 30

# Indexing a vector
my_vec <- c(10, 20, 30, 40)
print(my_vec[3]) # Output: [1] 30

Operator Precedence:

Just like in mathematics, operators in R have an order of precedence. Operations with higher
precedence are performed before operations with lower precedence. For example,
multiplication and division are performed before addition and subtraction. Parentheses () can
be used to override the default precedence.
Understanding and effectively utilizing these operators is crucial for writing efficient and
readable R code for data analysis and statistical computing.

Control Statements:
In R programming, control statements are fundamental constructs that allow you to dictate
the flow of execution in your code. They enable you to make decisions, repeat actions, and
handle different scenarios based on specific conditions. This makes your programs dynamic
and capable of responding to varying inputs and data.

Here are the main types of control statements in R:

1. Conditional Statements (Decision Making)


o if statement
o if-else statement
o if-else if-else statement
o ifelse() function
o switch() statement
2. Looping Statements (Iteration)
o for loop
o while loop
o repeat loop
3. Loop Control Statements
o break
o next

Let's explore each of these in detail with examples:

1. Conditional Statements (Decision Making)

These statements execute a block of code only if a specified condition evaluates to TRUE.

a) if Statement

Executes a block of code if the condition is TRUE.

Syntax:

R
if (condition) {
# code to be executed if condition is TRUE
}

Example:

R
x <- 10

if (x > 5) {
print("x is greater than 5")
}

b) if-else Statement

Executes one block of code if the condition is TRUE and another block if it's FALSE.

Syntax:

R
if (condition) {
# code to be executed if condition is TRUE
} else {
# code to be executed if condition is FALSE
}

Example:

R
temperature <- 28

if (temperature > 30) {


print("It's hot outside!")
} else {
print("It's not too hot.")
}

c) if-else if-else Statement (Nested if-else)

Allows for multiple conditions to be checked sequentially.

Syntax:

R
if (condition1) {
# code if condition1 is TRUE
} else if (condition2) {
# code if condition2 is TRUE
} else {
# code if no condition is TRUE
}
Example:

R
score <- 85

if (score >= 90) {


print("Grade: A")
} else if (score >= 80) {
print("Grade: B")
} else if (score >= 70) {
print("Grade: C")
} else {
print("Grade: Below C")
}

d) ifelse() Function

A vectorized version of if-else, useful for applying a condition to each element of a vector. It
returns a vector of results.

Syntax:

R
ifelse(test, yes, no)

Where:

● test: A logical vector (the condition).


● yes: Value to return if test is TRUE.
● no: Value to return if test is FALSE.

Example:

R
ages <- c(15, 22, 18, 30, 16)
can_vote <- ifelse(ages >= 18, "Yes", "No")
print(can_vote)
# Output: [1] "No" "Yes" "Yes" "Yes" "No"

e) switch() Statement

Useful for selecting one of many code blocks to execute based on the value of an expression.
It's often cleaner than long if-else if chains for specific value comparisons.

Syntax:

R
switch(expression,
case1 = result1,
case2 = result2,
...,
default_case = default_result # optional
)

Example (using character expression):

R
day_of_week <- "Tuesday"

greeting <- switch(day_of_week,


"Monday" = "Start of the week!",
"Tuesday" = "Taco Tuesday!",
"Wednesday" = "Hump Day!",
"Thursday" = "Almost Friday!",
"Friday" = "TGIF!",
"Weekend!" # Default if no match
)
print(greeting) # Output: "Taco Tuesday!"

Example (using numeric expression):

R
choice <- 2

result <- switch(choice,


"You chose option 1",
"You chose option 2",
"You chose option 3"
)
print(result) # Output: "You chose option 2"

2. Looping Statements (Iteration)

These statements allow you to repeatedly execute a block of code.

a) for Loop

Executes a block of code for each element in a sequence (vector, list, data frame columns,
etc.).

Syntax:

R
for (variable in sequence) {
# code to be executed for each element
}

Example (iterating over a vector):


R
fruits <- c("apple", "banana", "cherry")

for (fruit in fruits) {


print(paste("I love", fruit))
}
# Output:
# [1] "I love apple"
# [1] "I love banana"
# [1] "I love cherry"

Example (iterating with an index):

R
for (i in 1:5) {
print(paste("Number:", i))
}

b) while Loop

Repeats a block of code as long as a specified condition is TRUE. It's crucial to ensure that
the condition eventually becomes FALSE to avoid an infinite loop.

Syntax:

R
while (condition) {
# code to be executed as long as condition is TRUE
}

Example:

R
count <- 1

while (count <= 5) {


print(paste("Count is:", count))
count <- count + 1 # Increment count to eventually make condition FALSE
}
# Output:
# [1] "Count is: 1"
# [1] "Count is: 2"
# [1] "Count is: 3"
# [1] "Count is: 4"
# [1] "Count is: 5"

c) repeat Loop

Repeats a block of code indefinitely until an explicit break statement is encountered within
the loop.
Syntax:

R
repeat {
# code to be executed repeatedly
if (condition_to_break) {
break # exits the loop
}
}

Example:

R
i <- 1
repeat {
print(paste("Repeating...", i))
i <- i + 1
if (i > 3) {
break # Exit the loop when i is greater than 3
}
}
# Output:
# [1] "Repeating... 1"
# [1] "Repeating... 2"
# [1] "Repeating... 3"

3. Loop Control Statements

These statements allow you to alter the normal execution flow of loops.

a) break Statement

Terminates the loop immediately and transfers control to the statement immediately
following the loop.

Example:

R
for (i in 1:10) {
if (i == 5) {
print("Breaking loop at 5")
break # Exits the loop
}
print(i)
}
# Output:
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] "Breaking loop at 5"

b) next Statement

Skips the rest of the current iteration of the loop and proceeds to the next iteration.

Example:

R
for (i in 1:5) {
if (i == 3) {
print("Skipping number 3")
next # Skips the rest of this iteration
}
print(paste("Current number:", i))
}
# Output:
# [1] "Current number: 1"
# [1] "Current number: 2"
# [1] "Skipping number 3"
# [1] "Current number: 4"
# [1] "Current number: 5"

Functions:

In R programming, functions are self-contained blocks of code designed to perform a specific


task. They are a cornerstone of good programming practice, offering several significant
benefits:

● Reusability: Write a block of code once and use it multiple times throughout your
program or even in different projects.
● Modularity: Break down complex problems into smaller, manageable units, making
your code easier to understand, debug, and maintain.
● Abstraction: Hide complex implementation details, allowing users to focus on what
the function does rather than how it does it.
● Readability: Well-named functions improve the clarity and readability of your code.
● Reduced Errors: By centralizing logic in a function, you minimize the risk of
inconsistencies and errors that can arise from copying and pasting code.

R supports both built-in functions (pre-defined functions that come with R or its packages)
and user-defined functions (functions you create yourself).

1. Built-in Functions
R comes with a vast library of built-in functions for almost any data-related task. You've
likely already encountered some of them.

Examples of common built-in functions:

● mean(x): Calculates the arithmetic mean of a numeric vector x.


● sum(x): Calculates the sum of elements in a vector x.
● max(x): Finds the maximum value in a vector x.
● min(x): Finds the minimum value in a vector x.
● sd(x): Calculates the standard deviation of a vector x.
● length(x): Returns the number of elements in an object x.
● print(x): Displays the value of x on the console.
● c(...): Combines values into a vector.
● [Link](...): Creates a data frame.
● [Link](...): Reads data from a CSV file.
● plot(...): Creates various types of plots.
● paste(...): Concatenates strings.
● sqrt(x): Calculates the square root of x.
● log(x, base): Calculates the logarithm of x to a specified base.

Example usage:

R
numbers <- c(10, 20, 30, 40, 50)

print(mean(numbers)) # Output: 30
print(sum(numbers)) # Output: 150
print(max(numbers)) # Output: 50

text <- "Hello"


name <- "R User"
message <- paste(text, name, "!")
print(message) # Output: [1] "Hello R User !"

2. User-Defined Functions

You can create your own functions in R to encapsulate specific logic tailored to your needs.

Basic Syntax of a User-Defined Function:

R
function_name <- function(argument1, argument2, ...) {
# Function body: R code to perform the task
# Last evaluated expression is typically the return value (explicit 'return()' is optional)
return(result) # Optional: explicitly return a value
}

Components of a Function:
● function_name: The name you give to your function. It should be descriptive and
follow R's naming conventions (e.g., my_function, calculate_average).
● <- (assignment operator): Used to assign the function definition to function_name.
● function() keyword: This keyword indicates that you are defining a function.
● arguments (parameters): A comma-separated list of inputs that the function accepts,
enclosed in parentheses (). These are placeholders for values that will be passed when
the function is called. Arguments can have default values.
● {} (curly braces): The function body, containing the R statements that will be
executed when the function is called.
● return() (optional): Specifies the value(s) the function should send back to the caller.
If return() is not used, the function automatically returns the value of the last
evaluated expression in the function body.

Examples of User-Defined Functions:

Example 1: A simple function to add two numbers

R
# Define the function
add_numbers <- function(a, b) {
sum_result <- a + b
return(sum_result) # Explicitly return the sum
}

# Call the function


result1 <- add_numbers(5, 3)
print(result1) # Output: [1] 8

result2 <- add_numbers(10.5, 2.3)


print(result2) # Output: [1] 12.8

Example 2: Function without an explicit return()

The last evaluated expression is automatically returned.

R
multiply_numbers <- function(x, y) {
x * y # This expression's value will be returned
}

product <- multiply_numbers(4, 6)


print(product) # Output: [1] 24

Example 3: Function with default arguments

You can assign default values to arguments. If the user doesn't provide a value for that
argument when calling the function, the default value is used.
R
# Define a function to calculate power with a default exponent
calculate_power <- function(base, exponent = 2) {
result <- base ^ exponent
return(result)
}

# Call with both arguments


print(calculate_power(5, 3)) # Output: [1] 125 (5^3)

# Call without specifying exponent (uses default of 2)


print(calculate_power(7)) # Output: [1] 49 (7^2)

Example 4: Function accepting a vector and performing an operation

R
# Define a function to calculate descriptive statistics
get_summary_stats <- function(data_vector) {
if (![Link](data_vector)) {
stop("Input must be a numeric vector.") # Error handling
}

mean_val <- mean(data_vector, [Link] = TRUE)


median_val <- median(data_vector, [Link] = TRUE)
sd_val <- sd(data_vector, [Link] = TRUE)

# Return a list of results


return(list(
mean = mean_val,
median = median_val,
sd = sd_val,
n = length(data_vector)
))
}

# Call the function


my_data <- c(1, 5, 8, 2, 9, 3, NA, 7)
stats <- get_summary_stats(my_data)
print(stats)
# Output:
# $mean
# [1] 5
# $median
# [1] 5
# $sd
# [1] 3.05505
# $n
# [1] 8
Passing Arguments to Functions

You can pass arguments to R functions in several ways:

1. By Position (default): Arguments are matched to parameters based on their order in


the function call.

my_func <- function(a, b) { print(paste(a, b)) }


my_func("Hello", "World") # "Hello World"

2. By Name: Arguments are matched to parameters by their names, regardless of order.


This is highly recommended for clarity and to prevent errors when functions have
many arguments.

my_func <- function(a, b) { print(paste(a, b)) }


my_func(b = "World", a = "Hello") # "Hello World"

3. Mixing Position and Name: You can mix both, but positional arguments must come
before named arguments.

my_func <- function(a, b, c) { print(paste(a, b, c)) }


my_func("First", c = "Third", "Second") # Error: positional argument follows named
argument
my_func("First", "Second", c = "Third") # Works: "First Second Third"

Lazy Evaluation of Arguments

R uses "lazy evaluation" for function arguments. This means that arguments are only
evaluated when they are actually used within the function body. If an argument is not used, it
is never evaluated.

R
lazy_example <- function(a, b) {
print(paste("Value of a:", a))
# 'b' is never used, so it's not evaluated
}

# Call with a missing 'b' - no error because 'b' is not used


lazy_example(a = 10) # Output: [1] "Value of a: 10"

# If 'b' were used, it would cause an error:


# lazy_example_error <- function(a, b) {
# print(paste("Value of a:", a))
# print(paste("Value of b:", b))
#}
# lazy_example_error(a = 10) # Error: argument "b" is missing, with no default

Functions are central to programming effectively in R, enabling you to write clean, modular,
and maintainable code for all your data analysis and statistical tasks.

vectors,matrices,lists,data frames, factors and tables in R


programming:

1. Vectors

Vectors are the most basic data structure in R. They are one-dimensional arrays that can hold
a sequence of elements of the same data type. If you try to mix data types, R will coerce all
elements to the most flexible type (e.g., numbers to characters).

Key Characteristics:

● Homogeneous: All elements must be of the same type (numeric, integer, character,
logical, complex).
● One-dimensional: A sequence of elements.
● Created with c(): The c() function (combine or concatenate) is used to create vectors.

Examples:

R
# Numeric Vector
numeric_vec <- c(10, 20, 30, 40, 50)
print(numeric_vec)
print(class(numeric_vec)) # Output: [1] "numeric"

# Character Vector
char_vec <- c("apple", "banana", "cherry")
print(char_vec)
print(class(char_vec)) # Output: [1] "character"

# Logical Vector
logical_vec <- c(TRUE, FALSE, TRUE)
print(logical_vec)
print(class(logical_vec)) # Output: [1] "logical"

# Integer Vector (add L suffix to make it explicit integer)


integer_vec <- c(1L, 2L, 3L)
print(integer_vec)
print(class(integer_vec)) # Output: [1] "integer"

# Coercion Example (numeric becomes character)


mixed_vec <- c(1, "hello", 3.14)
print(mixed_vec)
print(class(mixed_vec)) # Output: [1] "character"

# Accessing elements
print(numeric_vec[1]) # First element (R uses 1-based indexing)
print(numeric_vec[c(2, 4)]) # Second and fourth elements
print(numeric_vec[-3]) # All elements except the third

2. Matrices

Matrices are two-dimensional, homogeneous data structures. They are essentially collections
of elements of the same data type arranged in rows and columns.

Key Characteristics:

● Homogeneous: All elements must be of the same type.


● Two-dimensional: Have rows and columns.
● Created with matrix(): The matrix() function is used to create matrices.
● Column-major order by default: Elements fill by column first, then by row. You
can change this with byrow=TRUE.

Examples:

R
# Create a 2x3 matrix
my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
print(my_matrix)
# Output:
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
print(class(my_matrix)) # Output: [1] "matrix" "array"

# Create a 3x2 matrix, filling by row


my_matrix_byrow <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2, byrow = TRUE)
print(my_matrix_byrow)
# Output:
# [,1] [,2]
# [1,] 1 2
# [2,] 3 4
# [3,] 5 6

# Accessing elements
print(my_matrix[1, 2]) # Element at row 1, column 2
print(my_matrix[2, ]) # All elements of row 2
print(my_matrix[, 3]) # All elements of column 3
print(my_matrix[c(1,2), c(2,3)]) # Subset of rows 1 and 2, columns 2 and 3

3. Lists

Lists are the most flexible data structure in R. They are one-dimensional, but they can hold
collections of objects of different data types and sizes. A list can even contain other lists,
vectors, matrices, data frames, or even functions.

Key Characteristics:

● Heterogeneous: Can contain elements of different data types.


● One-dimensional (conceptually): A sequence of elements, but each element can be a
complex object.
● Created with list(): The list() function is used to create lists.
● Elements can be named: Makes accessing elements more intuitive.

Examples:

R
# Create a list
my_list <- list("Alice", 25, TRUE, c(1, 2, 3), matrix(1:4, nrow=2))
print(my_list)
# Output:
# [[1]]
# [1] "Alice"
#
# [[2]]
# [1] 25
#
# [[3]]
# [1] TRUE
#
# [[4]]
# [1] 1 2 3
#
# [[5]]
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
print(class(my_list)) # Output: [1] "list"

# Create a named list


person_info <- list(
name = "Bob",
age = 30,
is_student = FALSE,
grades = c(90, 85, 92)
)
print(person_info)

# Accessing elements
print(my_list[[1]]) # Access first element by position (returns the element itself)
print(my_list[1]) # Access first element by position (returns a list containing that
element)
print(person_info$name) # Access by name using $ operator
print(person_info[["age"]]) # Access by name using double brackets
print(person_info[c("name", "grades")]) # Access multiple named elements (returns a sub-
list)

4. Data Frames

Data frames are the most commonly used data structure for storing tabular data in R. They
are essentially lists of vectors of equal length. Each vector represents a column, and each
element within the vector represents a row. Data frames are similar to tables in a relational
database or spreadsheets in Excel.

Key Characteristics:

● Tabular structure: Rows and columns.


● Heterogeneous columns: Each column (vector) can have a different data type, but all
elements within a column must be of the same type.
● Homogeneous rows: All rows have the same number of elements.
● Created with [Link](): The [Link]() function is used to create data frames.
● Columns are named: Default names are provided if not specified.

Examples:

R
# Create a data frame
students_df <- [Link](
Name = c("Alice", "Bob", "Charlie"),
Age = c(20, 22, 21),
Major = c("Math", "Physics", "Chemistry"),
GPA = c(3.8, 3.5, 3.9)
)
print(students_df)
# Output:
# Name Age Major GPA
# 1 Alice 20 Math 3.8
# 2 Bob 22 Physics 3.5
# 3 Charlie 21 Chemistry 3.9
print(class(students_df)) # Output: [1] "[Link]"

# Accessing elements
print(students_df$Name) # Access column by name using $
print(students_df[["Age"]]) # Access column by name using double brackets
print(students_df[, "Major"]) # Access column by name using square brackets
print(students_df[1, ]) # Access first row
print(students_df[c(1, 3), ]) # Access first and third rows
print(students_df[2, 3]) # Access element at row 2, column 3 (Major for Bob)

5. Factors

Factors are used to store categorical data in R. They are special vectors that represent levels
(categories) rather than raw values. This is particularly useful for statistical modeling, where
categorical variables need to be treated differently from continuous ones.

Key Characteristics:

● Categorical data: Ideal for variables like gender, education level, city, etc.
● Levels: Factors have predefined levels, which are the unique categories the data can
take.
● Ordered or Unordered: Factors can be ordered (e.g., "low" < "medium" < "high") or
unordered.
● Underlying integer representation: R stores factors as integers with labels mapped
to these integers.

Examples:

R
# Create a character vector
gender_char <- c("Male", "Female", "Female", "Male", "Male")
print(gender_char)

# Convert to a factor
gender_factor <- factor(gender_char)
print(gender_factor)
# Output:
# [1] Male Female Female Male Male
# Levels: Female Male (Levels are sorted alphabetically by default)
print(class(gender_factor)) # Output: [1] "factor"

# Check levels
print(levels(gender_factor)) # Output: [1] "Female" "Male"

# Create an ordered factor


education_levels <- factor(c("High School", "College", "PhD", "Masters", "College"),
levels = c("High School", "College", "Masters", "PhD"),
ordered = TRUE)
print(education_levels)
# Output:
# [1] High School College PhD Masters College
# Levels: High School < College < Masters < PhD
print([Link](education_levels)) # Output: [1] TRUE

# Factor in a data frame


survey_data <- [Link](
ID = 1:3,
Satisfaction = factor(c("Low", "High", "Medium"),
levels = c("Low", "Medium", "High"),
ordered = TRUE)
)
print(survey_data)
str(survey_data) # Shows data types, including factor levels

6. Tables (specifically "Frequency Tables")

In R, when people refer to "tables" in the context of data structures, they often mean the
output of functions like table() or ftable(), which generate frequency tables (contingency
tables) to summarize categorical data. These are not a distinct core data type like vectors or
data frames, but rather a specialized array type that is very commonly used for summarizing
data.

The output of table() is typically of class table or array.

Key Characteristics:

● Summarize counts: Show the frequency of occurrences for each unique value (level)
in one or more categorical variables.
● Used for categorical data: Works best with factors or character vectors.
● Multi-dimensional (for multiple variables): Can show cross-tabulations.

Examples:

R
# Frequency table for a single vector (factor)
gender_data <- factor(c("Male", "Female", "Male", "Female", "Female", "Male"))
gender_counts <- table(gender_data)
print(gender_counts)
# Output:
# gender_data
# Female Male
# 3 3
print(class(gender_counts)) # Output: [1] "table"

# Two-way frequency table (cross-tabulation)


city_data <- c("Hyderabad", "Bengaluru", "Chennai", "Hyderabad", "Bengaluru", "Chennai")
living_status <- c("Rent", "Own", "Rent", "Own", "Rent", "Own")

cross_tab <- table(city_data, living_status)


print(cross_tab)
# Output:
# living_status
# city_data Own Rent
# Bengaluru 1 1
# Chennai 1 1
# Hyderabad 1 1
# Convert a table to a data frame for easier manipulation
table_df <- [Link](cross_tab)
print(table_df)
# Output:
# city_data living_status Freq
# 1 Bengaluru Own 1
# 2 Chennai Own 1
# 3 Hyderabad Own 1
# 4 Bengaluru Rent 1
# 5 Chennai Rent 1
# 6 Hyderabad Rent 1

Summary of Data Structures in R:

Data
Dimensio Homogeneous/ Primary Creation
Structu Analogy
ns Heterogeneous Use Case Function
re
Basic A single
Vector 1D Homogeneous sequence c() column in
of values Excel
Rectangul
A grid of
Matrix 2D Homogeneous ar data of matrix()
numbers
same type
Collection A mixed-
List 1D Heterogeneous of diverselist() content
objects folder
Tabular An Excel
Data [Link]
2D Heterogeneous (columns) data (most spreadshe
Frame ()
common) et
Drop-
Categoric
down list
Factor 1D Homogeneous (categorical) al factor()
with
variables
options
Frequency A pivot
Table N-D Homogeneous (counts) table()
counts table

accessing input and output in R programming:


1. Input: Getting Data into R
a. Reading from the Console (User Input)
You can prompt the user for input directly within your R script using readline() or scan().
● readline(): Reads a single line of text from the console. It always returns a character
string, so you'll need to convert it if you expect a number.
R

# Example: Get user's name


user_name <- readline("Enter your name: ")
print(paste("Hello,", user_name))

# Example: Get user's age (and convert to numeric)


user_age_str <- readline("Enter your age: ")
user_age_num <- [Link](user_age_str)
print(paste("You are", user_age_num, "years old."))
print(class(user_age_num))
● scan(): Reads data into a vector or list. It's more versatile for reading multiple values
(numbers or strings) from the console, one per line.

# Example: Read multiple numbers


cat("Enter numbers, one per line. Press Enter twice to finish:\n")
my_numbers <- scan(what = numeric()) # what specifies the data type
print("You entered:")
print(my_numbers)

# Example: Read multiple words


cat("Enter words, one per line. Press Enter twice to finish:\n")
my_words <- scan(what = character())
print("You entered:")
print(my_words)
b. Reading from Files
This is the most common way to get data into R for analysis. R has specialized functions for
various file formats.
● CSV (Comma Separated Values) Files: [Link]() is the go-to for CSVs.

# Create a dummy CSV file for demonstration


# (You would typically have this file already)
[Link]([Link](Name = c("A", "B"), Age = c(25, 30)), "my_data.csv",
[Link] = FALSE)

# Read the CSV file


my_data <- [Link]("my_data.csv")
print(my_data)
# Output:
# Name Age
# 1 A 25
# 2 B 30
● Text Files: [Link]() is general-purpose for delimited text files. [Link]() is
similar but defaults to tab-separated.
R

# Create a dummy text file


writeLines(c("ID\tValue", "1\t100", "2\t200"), "my_text.txt")

# Read the text file (tab-separated)


text_data <- [Link]("my_text.txt", header = TRUE, sep = "\t")
print(text_data)
# Output:
# ID Value
# 1 1 100
# 2 2 200
● Excel Files: You typically need a package like readxl for .xlsx or .xls files.

# Install if you haven't already: [Link]("readxl")


library(readxl)

# Assuming you have an Excel file named 'my_excel_data.xlsx'


# For demonstration, let's pretend it exists.
# excel_data <- read_excel("my_excel_data.xlsx", sheet = "Sheet1")
# print(excel_data)
● Other Formats: R has packages for almost any data format (e.g., haven for SAS,
SPSS, Stata; jsonlite for JSON; XML for XML).

2. Output: Getting Data Out of R


a. Printing to the Console
● print(): Displays the value of an R object. It's the most common way to see results.

my_variable <- "Hello, R!"


print(my_variable)

my_vector <- c(1, 2, 3)


print(my_vector)
● cat(): Concatenates and prints R objects, often used for more controlled output,
including custom messages. It doesn't add quotes around strings or indices for vectors
like print().

name <- "Alice"


age <- 30
cat("Name:", name, "\nAge:", age, "\n") # \n for new line

cat("The sum is:", 10 + 5, "\n")


● message(): Used for generating diagnostic messages (e.g., warnings or informational
messages) that are often suppressed or redirected in non-interactive sessions.

message("This is an informational message.")


● warning(): Generates a warning message. Execution continues.

warning("Be careful, something might be wrong!")


● stop(): Halts execution and generates an error message.

# This line would stop your script


# stop("An unrecoverable error occurred!")
b. Writing to Files
● CSV Files: [Link]() is commonly used to save data frames to CSV.

my_results_df <- [Link](


Product = c("A", "B", "C"),
Sales = c(100, 150, 120)
)
[Link](my_results_df, "sales_results.csv", [Link] = FALSE)
# The '[Link] = FALSE' argument prevents R from writing row numbers as a
column.
● Text Files: [Link]() for delimited text files or writeLines() for writing character
vectors line by line.

# Write a data frame to a tab-separated file


[Link](my_results_df, "sales_results.txt", sep = "\t", [Link] = FALSE, quote
= FALSE)
# quote = FALSE prevents wrapping character fields in quotes.

# Write a vector of lines to a text file


lines_to_write <- c("First line of text.", "Second line of text.", "Last line.")
writeLines(lines_to_write, "my_output.txt")
● R Data Files (.RData or .rda): save() and load() are used to save and load R objects
(variables, data frames, functions, etc.) in R's native binary format. This is efficient
for preserving R-specific data types.

my_variable_to_save <- "Some important string"


my_df_to_save <- [Link](x = 1:3, y = letters[1:3])

save(my_variable_to_save, my_df_to_save, file = "my_r_objects.RData")


# To load them later:
# rm(list = ls()) # Clear workspace (for demonstration)
# load("my_r_objects.RData")
# print(my_variable_to_save)
# print(my_df_to_save)
● Saving a single object: saveRDS() and readRDS() are preferred for saving and
loading single R objects, as they are often more robust and less prone to name
conflicts when loading.

saveRDS(my_df_to_save, "single_df.rds")
# To load later:
# loaded_df <- readRDS("single_df.rds")
# print(loaded_df)
● Saving Plots: R's plotting functions often integrate with device functions like pdf(),
png(), jpeg(), etc., to save plots to files.

# Save a plot as a PNG


png("my_plot.png", width = 600, height = 400) # Open PNG device
plot(1:10, type = "l", main = "A Simple Plot") # Create plot
[Link]() # Close the device (saves the file)

# Save as PDF
pdf("my_plot.pdf")
hist(rnorm(100), main = "Histogram of Normal Data")
[Link]()

You might also like