TANSCHE : SMPTS33 - Mathematical Statistics with R Programming - Unit 2

R Programming Unit 2 – Vectors and Lists (TANSCHE)

📊 STATISTICS WITH R PROGRAMMING

Madurai Kamaraj University · II B.Sc. Mathematics, III Semester · TANSCHE Syllabus

ARO Study Circle

Chapter 2 · Vectors and Lists in R

Syllabus: Creating and combining vectors – Accessing Vector Elements – Modifying Vectors – Vector arithmetic and Recycling – Vector Element Sorting – Reading Vectors – Creating Lists – Accessing List elements – Updating List Elements – Merging Lists – List to Vector conversion

2.1 Vectors

A vector is the most basic and fundamental data structure in R. Think of a vector as a container that holds a sequence of elements, but with one important restriction: all elements in a vector must be of the same type. If you try to mix different types, R will automatically convert (coerce) them to a common type. The elements in a vector are officially called components.

  • Vector contains elements of the same type (logical, integer, double, character, complex, or raw).
  • Use typeof() to check the data type of a vector.
  • Use length() to find how many elements are in a vector.
  • A single value in R is actually a vector of length 1.

2.1.1 Creating Vectors

There are several ways to create vectors in R. The most common methods are using the colon operator, the c() function, and the seq() function.

(a) Colon (:) Operator

The colon operator creates a sequence of consecutive numbers.

# Creates a vector from 1 to 7 x <- 1:7 x # Creates a vector from 2.5 to 10.5 x <- 2.5:10.5 x # Creates a vector from 2.5 to 4.5 (stops at 4.5) x <- 2.5:4.7 x
[1] 1 2 3 4 5 6 7
[1] 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5
[1] 2.5 3.5 4.5

(b) c() Function

The c() function (combine) is the most common way to create vectors. Since all elements must be of the same type, R will automatically coerce different types following this order: logical → integer → double → character.

# All elements are coerced to double (numeric) x <- c(10, 2.5, TRUE) x typeof(x) # All elements are coerced to character x <- c(1, 2.8, TRUE, "apple") x typeof(x) # Find the length of the vector length(x)
[1] 10.0 2.5 1.0
[1] "double"
[1] "1" "2.8" "TRUE" "apple"
[1] "character"
[1] 4

(c) sequence (seq) Operator

For more complex sequences, use the seq() function. You can specify either the step size or the number of points in the interval.

# Creates a vector from 2 to 3 with step size 0.2 x <- seq(2, 3, by = 0.2) x # Creates a vector with length 3 from 1 to 5 x <- seq(1, 5, length = 3) x
[1] 2.0 2.2 2.4 2.6 2.8 3.0
[1] 1 3 5

2.1.2 Combining Vectors

Two or more vectors can be combined into one vector using the c() function. When combining vectors of different types, R will coerce all elements to the same type.

n <- c(2, 3, 4) m <- c("a", "b", "c", "d") # Combining vectors (numeric coerced to character) c(n, m)
[1] "2" "3" "4" "a" "b" "c" "d"

2.1.3 Accessing Vector Elements

Elements of a vector are accessed using indexing with square brackets []. The index can be an integer vector, a logical vector, or a character vector. Important: R uses 1‑based indexing (the first element is at index 1, not 0).

(a) Integer Vector as Index

s <- c("a", "b", "c", "d", "e") # Retrieve element at index 3 s[3] # Negative index returns all elements except that position s[-3] # Out of range index returns NA s[10] # Retrieve multiple elements using a numeric index vector s[c(2, 3)] # Duplicate values are allowed s[c(2, 3, 3)] # Elements can be retrieved in any order s[c(2, 1, 3)] # Using colon operator for a range s[2:4]
[1] "c"
[1] "a" "b" "d" "e"
[1] NA
[1] "b" "c"
[1] "b" "c" "c"
[1] "b" "a" "c"
[1] "b" "c" "d"

(b) Logical Vector as Index

When using a logical vector for indexing, R returns only the elements where the logical vector is TRUE. This is very useful for filtering.

s <- c(1, 2, 3, -5, -6) # Returns elements at positions where index is TRUE s[c(TRUE, FALSE, FALSE, TRUE, FALSE)] # Filter for negative numbers s[s < 0] # Filter for positive numbers s[s > 0]
[1] 1 -5
[1] -5 -6
[1] 1 2 3

(c) Character Vector as Index

This type of indexing is useful when vector elements have names.

v <- c("Jack", "Joe", "Tom") v # Assign names to each element names(v) <- c("First", "Second", "Third") names(v) # Retrieve element by name v["Second"] # Reverse order using character index vector v[c("Third", "First", "Second")]
[1] "Jack" "Joe" "Tom"
[1] "First" "Second" "Third"
Second
"Joe"
Third First Second
"Tom" "Jack" "Joe"

2.1.4 Modifying Vectors

You can modify specific elements of a vector using assignment. To truncate a vector, reassign a subset of it.

x <- c(10, 20, 30, 40, 50, 60) x # Modify the 2nd element x[2] <- 90 x # Modify all elements less than 30 x[x < 30] <- 5 x # Truncate x to first 4 elements x <- x[1:4] x
[1] 10 20 30 40 50 60
[1] 10 90 30 40 50 60
[1] 5 90 30 40 50 60
[1] 5 90 30 40

2.1.5 Deleting Vectors

To delete a vector completely, assign NULL to it.

x <- c(10, 20, 30, 40, 50, 60) x # Delete the vector x <- NULL x
[1] 10 20 30 40 50 60
NULL

2.1.6 Vector Arithmetic & Recycling

Vector arithmetic operations (addition, subtraction, multiplication, division, etc.) are performed element‑wise. When two vectors are of different lengths, the shorter vector is recycled (repeated) to match the length of the longer vector. A warning is given if the longer vector is not a multiple of the shorter one.

x <- c(10, 20, 30) y <- c(1, 2, 3) x y # Element-wise addition x + y # Single value is recycled to a vector of 1's x + 1 # Recycling with warning (4,5 is recycled to 4,5,4) y + c(4, 5)
[1] 10 20 30
[1] 1 2 3
[1] 11 22 33
[1] 11 21 31
[1] 5 7 7
Warning message: In y + c(4, 5) : longer object length is not a multiple of shorter object length

2.1.7 Vector Element Sorting

The sort() function sorts vector elements. By default, sorting is in ascending order. Use decreasing = TRUE for descending order. Important: Vectors are immutable, meaning the original vector remains unchanged.

x <- c(7, 1, 8, 3, 2, 6, 5, 2, 2, 4) # Sort in ascending order (default) sort(x) # Sort in descending order sort(x, decreasing = TRUE) # Original vector remains unchanged x # Sorting character strings flowers <- c("lotus", "rose", "jasmine", "daisy", "lilly") sort(flowers) sort(flowers, decreasing = TRUE) # Original character vector unchanged flowers
[1] 1 2 2 2 3 4 5 6 7 8
[1] 8 7 6 5 4 3 2 2 2 1
[1] 7 1 8 3 2 6 5 2 2 4
[1] "daisy" "jasmine" "lilly" "lotus" "rose"
[1] "rose" "lotus" "lilly" "jasmine" "daisy"
[1] "lotus" "rose" "jasmine" "daisy" "lilly"

2.1.8 Reading Vectors

The readline() function reads input from the user (terminal). It returns a single‑element character vector. Use conversion functions like as.integer(), as.double(), as.logical(), or as.complex() to convert to other types.

my.name <- readline(prompt = "Enter name: ") my.age <- readline(prompt = "Enter age: ") my.age <- as.integer(my.age) my.bool <- readline(prompt = "Enter (TRUE/FALSE): ") my.bool <- as.logical(my.bool) my.name my.age my.bool
[1] "Jeeva"
[1] 38
[1] TRUE
Important: Each readline() statement must be executed line by line. Selecting multiple statements at once will not work properly.

2.2 Lists

A list is a generic vector that can contain objects of different types. Unlike regular vectors, lists can hold numbers, strings, vectors, matrices, functions, or even other lists inside them. Lists are one of the most flexible data structures in R.

  • Lists can contain elements of different types.
  • A list can contain another list (nested lists).
  • Lists can also contain matrices or functions as elements.

2.2.1 Creating Lists

Lists are created using the list() function. Each argument becomes an element of the list.

# Creating a list with different types of elements n <- list(c(2,3,5), c("a","b","c","d","e"), c(TRUE,FALSE,TRUE,FALSE,FALSE), 3) n
[[1]]
[1] 2 3 5

[[2]]
[1] "a" "b" "c" "d" "e"

[[3]]
[1] TRUE FALSE TRUE FALSE FALSE

[[4]]
[1] 3

2.2.2 Accessing List Elements

List elements can be accessed using indexing similar to vectors. There are several ways: single square brackets [] return a sublist, double square brackets [[]] return the actual element, and the $ operator accesses named elements.

n <- list(c(2,3,5), c("a","b","c","d","e"), c(TRUE,FALSE,TRUE,FALSE,FALSE), 3) # Access second element (returns a sublist) n[2] # Access a slice (elements 2 through 4) n[c(2:4)] # Negative integer to exclude second component n[-2] # Index using logical vector n[c(TRUE,FALSE,FALSE,FALSE)] # Assign names to list components names(n) <- c("First", "Second", "Third", "Fourth") # Index using character vector (names) n[c("Second", "Fourth")] # Using $ operator to reference a member n$Fourth
[[1]]
[1] "a" "b" "c" "d" "e"

[[1]]
[1] "a" "b" "c" "d" "e"
[[2]]
[1] TRUE FALSE TRUE FALSE FALSE
[[3]]
[1] 3

[[1]]
[1] 2 3 5
[[2]]
[1] TRUE FALSE TRUE FALSE FALSE
[[3]]
[1] 3

[[1]]
[1] 2 3 5

$Second
[1] "a" "b" "c" "d" "e"
$Fourth
[1] 3

[1] 3

Double Square Brackets [[]]

Use [[]] to access the actual element directly (not as a sublist). This allows you to modify the element’s content.

n <- list(c(2, 3, 5), c("a", "b", "c", "d", "e"), c(TRUE, FALSE, TRUE, FALSE, FALSE), 3) # Access as sublist n[2] # Access the actual element and modify it n[[2]][1] <- "z" n[[2]]
[[1]]
[1] "a" "b" "c" "d" "e"

[1] "z" "b" "c" "d" "e"

2.2.3 Updating List Elements

You can add, delete, and update list elements. Elements can be added or removed at the end of a list, but any element can be updated regardless of position.

n <- list(c(2, 3, 5), c("a", "b", "c", "d", "e"), c(TRUE, TRUE), 3) # Add element at the end of the list n[5] <- "New element" n[5] # Remove the last element n[5] <- NULL # Print the 5th element (now NULL) n[5] # Update the 3rd element n[3] <- c("rose") n
[1] "New element"

[1] NULL

[[1]]
[1] 2 3 5

[[2]]
[1] "a" "b" "c" "d" "e"

[[3]]
[1] "rose"

[[4]]
[1] 3

2.2.4 Merging Lists

Multiple lists can be merged into one list using the c() function.

m <- list(c(2, 3, 5)) n <- list(c("a", "b", "c")) k <- list(c(TRUE, FALSE, TRUE)) # Merges three lists into one single list merged.list <- c(m, n, k) merged.list
[[1]]
[1] 2 3 5

[[2]]
[1] "a" "b" "c"

[[3]]
[1] TRUE FALSE TRUE

2.2.5 List to Vector Conversion

A list can be converted to a vector using the unlist() function. This is useful when you want to perform arithmetic operations on list elements.

# Create list1 and list2 list1 <- list(1:5) list1 list2 <- list(11:15) list2 # Convert the lists to vectors v1 <- unlist(list1) v2 <- unlist(list2) v1 v2 # Now add the vectors result <- v1 + v2 result
[[1]]
[1] 1 2 3 4 5

[[1]]
[1] 11 12 13 14 15

[1] 1 2 3 4 5
[1] 11 12 13 14 15
[1] 12 14 16 18 20

📋 Summary Table: Vectors vs Lists

FeatureVectorList
Element typesAll elements must be same typeCan contain different types
Creationc(), :, seq()list()
Indexing[][] (returns sublist), [[]] (returns element)
Named accessnames() then ["name"]$name or [["name"]]
Use caseHomogeneous dataHeterogeneous / complex data
Quick Reference Card for Vectors and Lists
Create vector: c(1, 2, 3) or 1:5 or seq(1, 10, by=2)
Create list: list(1, "a", TRUE)
Access vector element: v[3]
Access list element (sublist): l[2]
Access list element (actual): l[[2]]
Access named list element: l$name
Vector length: length(v)
Sort vector: sort(v) or sort(v, decreasing=TRUE)
Combine vectors/lists: c(v1, v2)
Convert list to vector: unlist(l)
Delete vector/list: v <- NULL

📘 R Programming · Unit 2 · Vectors and Lists

Prepared by ARO Study Circle

Post a Comment

0 Comments