Unit-2
Lists: Creating Lists, General List Operations, List Indexing Adding and Deleting List Elements, Getting the Size of a List, Extended Example: Text Concordance Accessing List Components and Values Applying Functions to Lists, DATA FRAMES: Creating Data Frames, Accessing Data Frames, Other Matrix- Like Operations
R List
R list is the object which contains elements of different types – like strings, numbers, vectors and another list inside it. R list can also contain a matrix or a function as its elements. The list is created using the list() function in R. In other words, a list is a generic vector containing other objects.
For example:
vec <- c(1,2,3)
char_vec <- c("Hadoop", "Spark", "Flink", "Mahout")
logic_vec <- c(TRUE, FALSE, TRUE, FALSE)
out_list <- list(vec, char_vec, logic_vec)
out_list
[[1]]
[1] 1 2 3
[[2]]
[1] "Hadoop" "Spark" "Flink" "Mahout"
[[3]]
[1] TRUE FALSE TRUE FALSE
R Predefined Lists
Lists for letters and month names are predefined:
letters
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"
LETTERS
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"
month.abb
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
month.name
[1] "January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December"
Create Lists in R Programming
Let’s create a list containing string, numbers, vectors and logical values.
For example:
list_data <- list("Red", "White", c(1,2,3), TRUE, 22.4)
print(list_data)
[[1]]
[1] "Red"
[[2]]
[1] "White"
[[3]]
[1] 1 2 3
[[4]]
[1] TRUE
[[5]]
[1] 22.4General List Operations in R
i) Give a Name to List Elements in R Language
Let’s create a list containing a vector, matrix, and list. Then we can give the names of each in the list.
For example:
data_list <- list(c("Jan","Feb","Mar"), matrix(c(1,2,3,4,-1,9), nrow = 2),list("Red",12.3))
names(data_list) <- c("Month", "Matrix", "Misc")
print(data_list)
$Month
[1] "Jan" "Feb" "Mar"
$Matrix
[,1] [,2] [,3]
[1,] 1 3 -1
[2,] 2 4 9
$Misc
$Misc[[1]]
[1] "Red"
$Misc[[2]]
[1] 12.3
ii) Access R List Elements
Let’s understand how to access lists elements in R programming.
Create an R list containing a vector, list and matrix.
In order to give names to the elements of the list:
data_list <- list(c("Jan","Feb","Mar"), matrix(c(1,2,3,4,-1,9), nrow = 2),list("Red",12.3))
names(data_list) <- c("Month", "Matrix", "Misc")
print(data_list [1]) or # print(data_list$Month)
$Month
[1] "Jan" "Feb" "Mar"
iii) Manipulate List elements in R Programming
Lets know how to manipulate the R list elements with the help of an example.
Create a list containing a vector, a matrix and a list.
data_list <- list(c("Jan","Feb","Mar"), matrix(c(1,2,3,4,-1,9), nrow = 2),list("Red",12.3))
For example:
Give names to the elements in the list
names(data_list) <- c("Month", "Matrix", "Misc")
Add an element at the end of the list.
data_list[4] <- "New element"
print(data_list[4])
[[1]]
[1] "New element"
Remove the last element in the list
data_list[4] <- NULL
print(data_list[4])
$<NA>
NULL
Update the 3rd Element in the list
data_list[3] <- "updated element"
print(data_list[3])
$Misc
[1] "updated element"
iv) Merge Lists in R Programming language
Now, merge many lists into one list by placing all the lists element inside one list()
function.
For example:
num_list <- list(1,2,3,4,5)
day_list <- list("Mon","Tue","Wed", "Thurs", "Fri")
merge_list <- c(num_list, day_list)
merge_list
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] 4
[[5]]
[1] 5
[[6]]
[1] "Mon"
[[7]]
[1] "Tue"
[[8]]
[1] "Wed"
[[9]]
[1] "Thurs"
[[10]]
[1] "Fri"
v) Convert R List to Vector
A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vector. To do this conversion, we can use the unlist() function. It takes the list as input and produces a vector.
For example:
Create lists.
int_list1 <- list(1:5)
print(int_list1)
[[1]]
[1] 1 2 3 4 5
int_list2 <- list(10:14)
print(int_list2)
[[1]]
[1] 10 11 12 13 14
Convert the lists to vectors
vec1 <- unlist(int_list1)
vec2 <- unlist(int_list2)
print(vec1)
[1] 1 2 3 4 5
print(vec2)
[1] 10 11 12 13 14
Now add the vectors
sum <- vec1 + vec2
print(sum)
[1] 11 13 15 17 19
R List Indexing
Accessing elements within a list is crucial. R provides three main ways to
index lists, each with distinct behavior:
i) Double Square Brackets
ii) Single Square Brackets
iii) Dolar Sign Operator
i) Double Square Brackets
It is used to extract a single element from a list. The result is the
content of that element, not a list. This is the primary way to get the
value of a specific component.
a numeric index (e.g., list[[1]]) or a character name (e.g., list[["name"]]).
ii) Single Square Brackets:
Used to extract a sub-list (a list containing one or more elements from a
list. The result is always a list.
numeric indices (e.g., list[c(1, 3)]) or
character names (e.g., list[c("name", "age")]).
iii) Dolar Sign Operator
A convenient shorthand for extracting a single named element.
Equivalent to [[ "name" ]]. It only works for named elements.
Example- For Double square brackets
person_details <- list(
name = "Rama",
age = 30,
is_student = FALSE,
grades = c(85, 92, 78),
address = list(
street = "123 Main St",
city = "vsp"
)
)## For character
Using [[...]] - Extracts the content/value of the element
name_val <- person_details[[1]]
print(name_val)
[1] "Rama"
print(typeof(name_val))
[1] "character"
## For Numeric
age_val <- person_details[["age"]]
print(age_val)
[1] 30
print(typeof(age_val))
[1] "double"
## For Single square Brackets
grades_vec <- person_details["grades"]
print(grades_vec)
[1] 85 92 78
# Using $ - Shorthand for named elements, equivalent to [[ "name" ]]
name_val_dollar <- person_details$name
print(name_val_dollar)
[1] "Rama"
Getting the Size of a ListThe length() function is used to get the number of top-level elements in
a list.
Examples:
my_list <- list(a = 1, b = "two", c = TRUE, d = c(4, 5, 6))
length(my_list)
[1] 4
# For nested lists, length() only counts top-level elements
nested_list <- list(item1 = 10, item2 = list(sub_a = "X", sub_b = "Y"))
length(nested_list)
[1] 2
Text Concordance
A text concordance is an alphabetical list of the principal words in a text, with their immediate contexts. This example demonstrates how lists can be used to store complex data structures, where each word is a named element containing a vector of line numbers where it appears.
For example -
To create a list where each unique word from our text is an element. The value of each element will be a vector containing the line numbers where that word was found.Step 1: Define the Sample Text
We'll store our text as a character vector, where each element represents a line.
# Our sample text, with each element as a line
my_text <- c( "R is a powerful language for data analysis.", "Learning R is fun and useful for statistics.", "The R language is open-source and free to use.")
Step 2: Create an Empty List to Store the Concordance. This empty list will be our final result. We will add words and their line numbers to it as we go.# Initialize an empty list to store the results concordance_list <- list()
Step 3: Loop Through Each Line of the Text
We'll use a for loop to process the text line by line.
# Loop through each line of the text using a line counter
for (line_number in seq_along(my_text)) {
# Get the current line
line <- my_text[line_number]
# Process the line to get individual words
# First, convert to lowercase to treat "The" and "the" as the same word
line_lower <- tolower(line)
# Split the line into words based on spaces and punctuation
# The `strsplit` function returns a list, so we take the first element `[[1]]`
words <- strsplit(line_lower, "[^a-z]+")[[1]]
# Remove any empty strings that might result from splitting (e.g., at the end of a sentence)
words <- words[words != ""]
# Now, loop through the words in the current line
for (word in words) {
# Check if the word is already a key in our concordance list
if (word %in% names(concordance_list)) {
# If the word exists, append the current line number to its vector
concordance_list[[word]] <- c(concordance_list[[word]], line_number)
} else {
# If the word is new, create a new entry for it with the current line number
concordance_list[[word]] <- line_number
}
}
}Step 4: View the Result
Now, let's print our concordance_list to see the final output.
# Print the final concordance list
print(concordance_list)
Expected Output: $r
[1] 1 2 3
$is
[1] 1 2 3
$a
[1] 1
$powerful
[1] 1
$language
[1] 1 3
$`for`
[1] 1 2
$data
[1] 1
$analysis
[1] 1
$learning
[1] 2
$fun
[1] 2
$and
[1] 2 3
$useful
[1] 2
$statistics
[1] 2
$the
[1] 3
$open
[1] 3
$source
[1] 3
$free
[1] 3
$to
[1] 3
$use
[1] 3
Applying Functions to Lists
(i) c function in R
The c function in R combines the parameter into a list and converts them to the
same type.
For example:
c("April", 4)
[1] "April" "4"
typeof("4")
[1] "character
(ii) When ever one need to perform a repetitive tasks on the list elements and avoid the more complex codes (like for loop etc..) R provides the apply family of functions.
They are (i) lapply function
(ii) sapply function
These functions are designed to apply a function to every element of a list without manual loop.
(i) lapply function: The "l" in lapply function stands for list. This functions always returns to list.
The lapply() and sapply() functions are powerful tools for applying a function to each
element of a list (or vector).
lapply(X, FUN, ...): Applies FUN to each element of X and always returns a
list.
For example:
my_list <- list(
vector1 = c(10, 20, 30),
vector2 = c(5, 6, 7, 8),
vector3 = c(100, 200)
)
mean_list <- lapply(my_list, mean)
print(mean_list)
$vector1[1] 20
$vector2[1] 6.5
$vector3[1] 150
Example-2
my_numbers_list <- list(vec1 = 1:5, vec2 = 10:12, vec3 = 7)
# Using lapply to calculate the sum of each vector in the list
sums_list <- lapply(my_numbers_list, sum)
print(sums_list)
$vec1
[1] 15
$vec2
[1] 33
$vec3
[1] 7
sums_vector <- sapply(my_numbers_list, sum)
print(sums_vector)
vec1 vec2 vec3 15 33 7
Example-3:
employee_data <- list(
emp1 = list(name = "Alice", dept = "HR", salary = 60000),
emp2 = list(name = "Bob", dept = "IT", salary = 85000),
emp3 = list(name = "Charlie", dept = "HR", salary = 70000)
)
# Our goal is to get a vector of all the salaries.
# Using lapply (returns a list)
salary_list <- lapply(employee_data, function(emp) { emp$salary })
print(salary_list)
# Output:
# $emp1
# [1] 60000
#
# $emp2
# [1] 85000
#
# $emp3
# [1] 70000
(ii) sapply function:
The "s" stands for simplify. This function works like lapply function but it tries to simplify the result into a more convenient data structures like a vector or matrix. Applies FUN to each element of X and tries to
simplify the result into a vector or matrix if possible; otherwise, returns a list.
sapply(X, FUN, ..., simplify = TRUE)
Example-1:
my_list <- list( vector1 = c(10, 20, 30), vector2 = c(5, 6, 7, 8), vector3 = c(100, 200))
# Use sapply to get the mean of each vectormean_vector <- sapply(my_list, mean)
print(mean_vector)
# Output (a named vector, which is much cleaner):# vector1 vector2 vector3
# 20.0 6.5 150.0
Example-2: # Using sapply (returns a vector)
salary_vector <- sapply(employee_data, function(emp) { emp$salary })print(salary_vector)
# Output:
# emp1 emp2 emp3
# 60000 85000 70000
# The sapply result is much easier to work with for calculations
mean_salary <- mean(salary_vector)
print(mean_salary)
# [1] 71666.67
R Data Frame
Data Frames in R
Data frames are the most commonly used data structure for storing tabular data in R. They are essentially a list of vectors of equal length, forming a rectangular data table, example- spreadsheet or a SQL table.
1. Creating Data Frames
Data frames are typically created using the data.frame() function, where each argument becomes a column.
Characteristics of Data Frames:
Two-dimensional: Rows and columns.
Heterogeneous: Columns can have different data types (e.g., one column can be numeric, another character, another logical).
Each column is a vector: All elements within a single column must be of the same type.
All columns must have the same length: This ensures the rectangular structure.
For example-
## Create data structures
Name = c("Alice", "Bob", "Charlie", "Diana"),
Age = c(22, 25, 20, 23),
Gender = c("F", "M", "M", "F"),
Enrolled = c(TRUE, TRUE, FALSE, TRUE)
## Creating data frame
df_students <- data.frame(
Name = c("Alice", "Bob", "Charlie", "Diana"),
Age = c(22, 25, 20, 23),
Gender = c("F", "M", "M", "F"),
Enrolled = c(TRUE, TRUE, FALSE, TRUE)
)
print(df_students)
# Output:
# Name Age Gender Enrolled # 1 Alice 22 F TRUE # 2 Bob 25 M TRUE # 3 Charlie 20 M FALSE # 4 Diana 23 F TRUE
Accessing Data Frames
Data frames can be accessed using similar indexing methods as lists and matrices, leveraging their hybrid nature.
$ (Dollar Sign Operator): Most common and readable way to access a single column by name.
[[...]] (Double Square Brackets): Access a single column by name (as a string) or by numeric index. Returns a vector.
[...] (Single Square Brackets):
df[row_index, col_index]: Access specific rows and columns.
df[, col_index]: Access entire columns.
df[row_index,]: Access entire rows.
Returns a data frame if multiple rows/columns are selected, or if drop = FALSE is used. Otherwise, it might simplify to a vector if a single column is selected.
df_students <- data.frame( Name = c("Alice", "Bob", "Charlie", "Diana"), Age = c(22, 25, 20, 23),
Gender = c("F", "M", "M", "F"), Enrolled = c(TRUE, TRUE, FALSE, TRUE)
)
## 1. Accessing columns using $ (most common for single columns) ages <- df_students$Age print(ages) ## Output: 22 25 20 23
print(class(ages)) # Output: "numeric"
## 2. Accessing columns using [[...]] (by name or index)
gender_col <- df_students[["Gender"]] print(gender_col)
# Output: F M M F
print(class(gender_col))
# Output: "factor"
## 3. Accessing rows and columns using [...]
# Access element at row 2, column 3sb_gender <- df_students[2, 3]
print(bob_gender)
# Output: M
Other Matrix-Like Operations
Since data frames are essentially lists of vectors that form a rectangular structure, many operations that work on matrices can also be applied to data frames (especially if the data frame contains only numeric columns).
Important Operations:
dim(): Get dimensions (rows, columns).
nrow() and ncol(): Get number of rows and columns.
colnames() and rownames(): Get or set column and row names.
head() and tail(): View the first/last few rows.
summary(): Provides descriptive statistics for each column.
t() (transpose): Transpose the data frame (can be tricky with mixed types).
rbind() and cbind(): Combine data frames by ##rows or columns.
df_sales <- data.frame( Product = c("A", "B", "C", "D", "E"), Region = c("East", "West", "East", "Central", "West"), Sales = c(100, 150, 120, 80, 200), Units = c(10, 15, 12, 8, 20)
)
# Dimensions
dim(df_sales)
# Output: 5 4
nrow(df_sales)
# Output: 5
ncol(df_sales)
# Output: 4
## Column Names
colnames(df_sales)
# Output: "Product" "Region" "Sales" "Units"
# Row Names (default are row numbers)
rownames(df_sales)
# Output: "1" "2" "3" "4" "5"
# Set custom row names (e.g., product IDs)
rownames(df_sales) <- c("P001", "P002", "P003", "P004", "P005")
print(df_sales)
## output: [1] "PD1" "PD2" "PD3" "PD4" "PD5"
# Viewing top/bottom rows
head(df_sales) # First 6 rows (or all if < 6)
tail(df_sales, 2) # Last 2 rows
# Transposing a data frame
transposed_df <- t(df_sales)
print(transposed_df)
# Adding a new column# Calculate 25% profit
df_sales$profit=df_sales$Sales*0.25
print(df_sales$profit)
print(df_sales)
output Product Region Sales Units ProfitA A East 100 10 25.0B B West 150 15 37.5C C East 120 12 30.0D D Central 80 8 20.0E E West 200 20 50.0
# Deleting a column
df_sales$profit=NULL
print(df_sales)
Product Region Sales Units
1 A East 100 10
2 B West 150 15
3 C East 120 12
4 D Central 80 8
5 E West 200 20
Combining Data Frames using rbind and cbind functions:
In R, cbind() and rbind() are two essential functions used to combine data structures. They are short for column bind and row bind, respectively. They are used to join vectors, matrices, or data frames together, and they work by combining these objects either side-by-side or stacked on top of each other.
cbind() - column bind joins the objects side-by-side, creating a object with more columns.
# Create two data frames
df1 <- data.frame(ID = 1:3, Name = c("A", "B", "C"))
df2 <- data.frame(Score = c(90, 85, 92), Pass = c(TRUE, FALSE, TRUE))
# Combine them by columns
combined_df <- cbind(df1,df2)
print(combined_df)
# Output:
ID Name Score Pass1 1 A 90 TRUE
2 2 B 85 FALSE 3 3 C 92 TRUE
rbind() - stacks the objects on top of each other, creating new object with more rows.
# Create two data frames
df1 <- data.frame(ID = 1:3, Name = c("A", "B", "C"))
df2 <- data.frame(ID = 4:6, Name = c(TRUE, FALSE, TRUE))
# Combine them by rows
combined_df <- rbind(df1,df2)
print(combined_df)
ID Name1 1 A2 2 B3 3 C4 4 TRUE5 5 FALSE6 6 TRUE
Comments
Post a Comment