0% found this document useful (0 votes)
6 views36 pages

R Programming: Arrays & Data Frames Guide

The document provides an overview of R programming data structures, focusing on arrays, data frames, and factors. It explains how to create, access, and manipulate these structures using various functions in R, including examples and expected outputs. Key concepts such as combining arrays and data frames, checking for element existence, and modifying factor levels are also covered.

Uploaded by

vk3573373
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)
6 views36 pages

R Programming: Arrays & Data Frames Guide

The document provides an overview of R programming data structures, focusing on arrays, data frames, and factors. It explains how to create, access, and manipulate these structures using various functions in R, including examples and expected outputs. Key concepts such as combining arrays and data frames, checking for element existence, and modifying factor levels are also covered.

Uploaded by

vk3573373
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

SIP-I on

R Programming
By
Dr. Devanshu Tiwari
Assistant Professor
Centre for Computer Science and Business Management
MITS-DU, Gwalior
12/13/2024
Day 5 contents
R Data Structures
• R Arrays
• R Data Frames
• R Factors

12/13/2024
R Data Structures
R Arrays
An Array is a data structure which can store data of the same type in more than
two dimensions.
The only difference between vectors, matrices, and arrays are
Vectors are uni-dimensional arrays
Matrices are two-dimensional arrays
Arrays can have more than two dimensions
Before we learn about arrays, make sure you know about R matrix and R
vector.

Create an Array in R
In R, we use the array() function to create an array.
The syntax of the array() function is
12/13/2024
R Data Structures
R Arrays

Here,
c(1:12) - a vector with values from 1 to 12
dim = c(2,3,2) - create two matrices of 2 by
3 dimension
Finally, the numbers from 1 to 12 that are
arranged in two 2 by 3 matrices are printed.

12/13/2024
R Data Structures
R Arrays

Access Array Elements


We use the vector index operator [ ] to access specific elements of an array in R.
The syntax to access an array element is

12/13/2024
R Data Structures
R Arrays

In the above example, we have created


an array named array1 with two 2 by 3
matrices. Notice the use of index
operator [],

Here, [1, 3, 2] specifies we are


trying to access element present at
the 1st row, 3rd column of the 2nd
matrix i.e. 11.

12/13/2024
R Data Structures
R Arrays
Access Entire Row or Column
In R, we can also access the entire row or column based on the value passed inside [].
[c(n), ,mat_level] - returns the entire element of the nth row.
[ ,c(n), mat_level] - returns the entire element of the nth column.

Here,
array1[,c(2),1] - access 2nd column elements of 1st matrix
12/13/2024 array1[c(1), ,2] - access 1st row of 2nd matrix
R Data Structures
R Arrays
Check if Element Exists
In R, we use the %in% operator to check if the specified element is present in the matrix or not and
returns a boolean value.
TRUE - if specified element is present in the matrix
FALSE - if specified element is not present in the matrix
For example,

Here,
11 is present in array1, so the
method returns TRUE
13 is not present in array1, so the
method returns FALSE

12/13/2024
R Data Structures
R Arrays
Length of Array in R
In R, we can use the length() function to find the number of elements present inside the array. For
example,

Here, we have used length()


to find the length of array1.
Since there are two 2 by 3
matrices the length()
function returns 12.

12/13/2024
R Data Structures
R Arrays examples Programs
Program 1: Creating a Simple Array
This program demonstrates how to create an array in R.

# Create a 3D array with two 3x2 matrices


array1 <- array(c(1:12), dim = c(3, 2, 2))
# Print the array
print("Array Elements:")
print(array1)

Expected Output
The output will display a 3D array with two 3x2 matrices, populated with numbers from 1 to
12.

12/13/2024
R Data Structures
R Arrays examples Programs
Program 2: Access Specific Elements in an Array
This program shows how to access specific elements in an array.

# Create an array
array1 <- array(c(1:12), dim = c(2, 3, 2))
# Access specific elements
cat("Element at [1, 2, 1]:", array1[1, 2, 1], "\n")
cat("Element at [2, 3, 2]:", array1[2, 3, 2], "\n")

Expected Output
The output will display the elements located at specific positions in the array, such as
[1, 2, 1] and [2, 3, 2].

12/13/2024
R Data Structures
R Arrays examples Programs
Program 3: Access Entire Rows or Columns
This program demonstrates how to access an entire row or column from an array.

# Create an array
array1 <- array(c(1:12), dim = c(3, 4, 1))
# Access an entire row
cat("Second row of the array:\n")
print(array1[2, , ])
# Access an entire column
cat("Third column of the array:\n")
print(array1[, 3, ])

Expected Output
The output will show all elements from the second row and third column of the array.
12/13/2024
R Data Structures
R Arrays examples Programs
Program 4: Check if an Element Exists in an Array
This program demonstrates the use of the %in% operator to check for the existence of an element in an
array.

# Create an array
array1 <- array(c(1:12), dim = c(2, 3, 2))

# Check if elements exist


cat("Does the value 8 exist in the array?:", 8 %in% array1, "\n")
cat("Does the value 15 exist in the array?:", 15 %in% array1, "\n")

Expected Output
The output will display TRUE for 8 and FALSE for 15, based on their presence in the array.

12/13/2024
R Data Structures
R Arrays examples Programs
Program 5: Combine Two Arrays
This program demonstrates combining arrays using the abind package
# Load the required package
if (!requireNamespace("abind", quietly = TRUE)) {
[Link]("abind")
}
library(abind)

# Create two arrays


array1 <- array(c(1:6), dim = c(2, 3, 1))
array2 <- array(c(7:12), dim = c(2, 3, 1))

# Combine arrays along a new dimension


combined_array <- abind(array1, array2, along = 3)

# Print the combined array


print("Combined Array:")
print(combined_array)

12/13/2024
R Data Structures
R Data Frames
A data frame is a two-dimensional data structure which can store data in tabular format.
Data frames have rows and columns and each column can be a different vector. And
different vectors can be of different data types.
Before we learn about Data Frames, make sure you know about R vector.
Create a Data Frame in R
In R, we use the [Link]() function to create a Data Frame.
The syntax of the [Link]() function is

12/13/2024
R Data Structures
R Data Frames

In the above example, we


have used the [Link]()
function to create a data
frame named dataframe1.
Notice the arguments
passed inside [Link](),

12/13/2024
R Data Structures
R Data Frames

12/13/2024
R Data Structures
R Data Frames
Access Data Frame Columns
There are different ways to extract columns from a data frame. We can use [ ], [[ ]], or $ to
access specific column of a data frame in R. For example,
In the above example, we have created a
data frame named dataframe1 with three
columns Name, Age, Vote.

Here, we have used different operators to


access Name column of dataframe1.

Accessing with [[ ]] or $ is similar.


However, it differs for [ ], [ ] will return
us a data frame but the other two will
reduce it into a vector and return a
vector.

12/13/2024
R Data Structures
R Data Frames
Combine Data Frames
In R, we use the rbind() and the cbind() function to combine two data frames together.

rbind() - combines two data frames vertically


cbind() - combines two data frames horizontally
Combine Vertically Using rbind()
If we want to combine two data frames vertically, the column name of the two data frames must be
the same. For example,

12/13/2024
R Data Structures
R Data Frames

Here, we have used the rbind()


function to combine the two data
frames: dataframe1 and
dataframe2 vertically.

12/13/2024
R Data Structures
R Data Frames
Combine Horizontally Using cbind()
The cbind() function combines two or more data frames horizontally. For example,

Here, we have used cbind() to combine


two data frames horizontally.

Note: The number of items on each


vector of two or more combining data
frames must be equal otherwise we
will get an error: arguments imply
differing number of rows or columns.

12/13/2024
R Data Structures
R Data Frames
Length of a Data Frame in R
In R, we use the length() function to find the number of columns in a data frame. For example,

Here, we have used length() to find the


total number of columns in dataframe1.
Since there are 3 columns, the length()
function returns 3.

12/13/2024
R Data Structures
R Data Frames
1. Create and Access a Data Frame
# Create a data frame
students <- [Link](
Name = c("Alice", "Bob", "Charlie"),
Age = c(20, 22, 19),
Major = c("Math", "Physics", "Computer Science"),
Passed = c(TRUE, TRUE, FALSE)
)

# Access specific columns and rows


print("Entire Data Frame:")
print(students)

print("Access 'Name' column:")


print(students$Name)

print("Access second row:")


print(students[2, ])

12/13/2024
R Data Structures
R Data Frames
2. Add and Modify Columns
# Create a data frame
employees <- [Link](
EmployeeID = c(101, 102, 103),
Department = c("HR", "IT", "Finance"),
Salary = c(50000, 60000, 70000)
)

# Add a new column


employees$Experience <- c(5, 3, 7)

# Modify existing column


employees$Salary <- employees$Salary + 5000

print("Updated Data Frame:")


print(employees)

12/13/2024
R Data Structures
R Data Frames
3. Filter Rows Based on Conditions
# Create a data frame
products <- [Link](
ProductID = c(1, 2, 3, 4, 5),
Price = c(100, 200, 300, 400, 500),
InStock = c(TRUE, FALSE, TRUE, TRUE, FALSE)
)

# Filter products with price > 250


expensive_products <- products[products$Price > 250, ]

# Filter products that are in stock


in_stock_products <- products[products$InStock == TRUE, ]

print("Products with price > 250:")


print(expensive_products)

print("Products in stock:")
print(in_stock_products)
12/13/2024
R Data Structures
R Data Frames
4. Combine Two Data Frames
# Create two data frames
df1 <- [Link](
Name = c("Alice", "Bob"),
Age = c(20, 22)
)

df2 <- [Link](


Name = c("Charlie", "David"),
Age = c(19, 21)
)

# Combine data frames using rbind()


combined_df <- rbind(df1, df2)

print("Combined Data Frame:")


print(combined_df)

12/13/2024
R Data Structures
R Data Frames
5. Summarize and Analyze Data Frame
# Create a data frame
sales <- [Link](
Month = c("January", "February", "March"),
Sales = c(15000, 20000, 25000),
Expenses = c(8000, 10000, 12000)
)
# Add a column for Profit
sales$Profit <- sales$Sales - sales$Expenses
# Calculate total sales
total_sales <- sum(sales$Sales)
# Calculate average profit
average_profit <- mean(sales$Profit)
print("Sales Data Frame:")
print(sales)
cat("Total Sales:", total_sales, "\n")
cat("Average Profit:", average_profit, "\n")

12/13/2024
R Data Structures
R Factors
A Factor is a data structure that is used to work with categorizable datas.

Suppose a data field such as marital status may contain only values from single, married, separated, divorced,
or widowed.

In such a case, we know the possible values beforehand and these predefined, distinct values are called levels
of a factor.
Create a Factor in R
In R, we use the factor() function to create a factor. Once a factor is created, it can only contain predefined set
values called levels. The syntax for creating a factor is:

Here, factor() takes a vector as an argument.

12/13/2024
R Data Structures
R Factors

In the above example, we have used


the factor() function to create the
factor named students_gender.

Notice while printing


students_gender, we get two outputs

All the vectors items


predefined possible values we know
beforehand i.e. levels of
students_gender

12/13/2024
R Data Structures
R Factors
Access Factors Elements
Accessing vector elements is similar to that of vectors. We use the index number. For example,

In this example, we have used the index


number to access elements of the
students_gender

students_gender[1] - returns the 1st


element of students_gender i.e "male"
students_gender[4] - returns the 4th
element of students_gender i.e.
"transgender"
Note that each time we access and print
factor elements we get a level of factor
too.

12/13/2024
R Data Structures
R Factors
Modify Factor Element
To change a vector element, we can simply reassign a new value to the specific index. For
example,

12/13/2024
R Data Structures
R Factors
1. Create and Access a Factor
# Create a factor representing students' grades
grades <- factor(c("A", "B", "C", "A", "B", "C", "A"))

# Print the factor


print("Grades Factor:")
print(grades)

# Access a specific element


print("Access 2nd Element:")
print(grades[2])

# Access levels of the factor


print("Levels of the Factor:")
print(levels(grades))
12/13/2024
R Data Structures
R Factors
2. Change the Levels of a Factor
# Create a factor for marital status
marital_status <- factor(c("single", "married", "single", "divorced", "married"))

# Change the levels of the factor


levels(marital_status) <- c("single", "married", "divorced", "widowed")

# Print the factor with updated levels


print("Updated Marital Status Factor:")
print(marital_status)

# Print levels of the updated factor


print("Updated Levels:")
print(levels(marital_status))

12/13/2024
R Data Structures
R Factors
3. Recode Factor Levels
# Create a factor representing department codes
departments <- factor(c("HR", "IT", "Finance", "IT", "HR", "Finance"))

# Recode the factor levels to more descriptive labels


departments <- factor(departments, levels = c("HR", "IT", "Finance"), labels = c("Human
Resources", "Information Technology", "Finance Department"))

print("Recode Factor Levels:")


print(departments)

12/13/2024
R Data Structures
R Factors
4. Count Frequency of Each Factor Level
# Create a factor representing product categories
categories <- factor(c("Electronics", "Clothing", "Electronics", "Furniture", "Clothing",
"Furniture", "Electronics"))

# Count the frequency of each level


category_count <- table(categories)

# Print the frequency of each category


print("Category Frequency Count:")
print(category_count)

12/13/2024
R Data Structures
R Factors
5. Modify Factor Elements
# Create a factor for customer satisfaction
satisfaction <- factor(c("Excellent", "Good", "Poor", "Good", "Excellent"))

# Modify a factor element (change 1st element from "Excellent" to "Good")


satisfaction[1] <- "Good"

# Print modified factor


print("Modified Satisfaction Factor:")
print(satisfaction)

12/13/2024

You might also like