Vectors and Lists

Topics: vector, list, collection, multiple data storing

In R, we use Vectors for collections of the same type (like a list of ages) and Lists for collections that can hold different types (like a patient record).

Creating Vectors and Lists

Vectors are created using c() (combine).

# Vector of patient names
patients <- c("Alice", "Ben", "Carla", "David")
patients                               # "Alice" "Ben"   "Carla" "David"

# Vector of blood pressure readings
bp_readings <- c(120, 130, 110, 140)
# Print
bp_readings                            # 120 130 110 140

# Lists can store mixed data types
# Print
patient_info <- list("John Doe", 45, 72.5, TRUE)
# Print
patient_info
# Output
# [[1]]
# [1] "John Doe"

# [[2]]
# [1] 45

# [[3]]
# [1] 72.5

# [[4]]
# [1] TRUE
Accessing Items (1-Based Indexing)

Important: In R, indexing starts at 1.

# Accessing items
print(patients[1])   # First patient:  Alice
print(patients[2])   # Second patient: Ben
print(patients[4])   # Fourth patient: David

In clinical data, indexing retrieves specific records or results.

Modifying Collections
patients <- c("Alice", "Ben")

# Adding items
patients <- c(patients, "Carla")         # Add to end
print(patients)                          # "Alice" "Ben" "Carla"

# Removing items (using negative index)
patients <- patients[-1]                 # Removes the FIRST item
print(patients)                          # "Ben" "Carla"

# Getting total count
length(patients)                         # 2
Vector Slicing

Slicing in R uses the start:stop syntax (both ends inclusive).

temperatures <- c(36.5, 37.1, 36.8, 37.5, 38.0, 36.9)

print(temperatures[2:4])   # 2nd to 4th readings: 37.1 36.8 37.5
print(temperatures[1:3])   # First 3 readings:    36.5 37.1 36.8