Named Lists

Topics: list, store values, key-value pairs

In R, Named Lists are used to store data in key-value pairs. They’re perfect for organizing related information of different types!

Creating Named Lists

Lists are great for storing structured data — like a patient’s demographic information, diagnosis, and vital signsall in one variable.

# Empty list
empty_list <- list()

# List with data
patient_record <- list(
    name        = "John Doe",
    age         = 45,
    sex         = "Male",
    diagnosis   = "Hypertension",
    bp          = "140/90",
    is_admitted = TRUE
)

print(patient_record)
# $name
# [1] "John Doe"
#
# $age
# [1] 45
#
# $sex
# [1] "Male"
#
# $diagnosis
# [1] "Hypertension"
#
# $bp
# [1] "140/90"
#
# $is_admitted
# [1] TRUE
Accessing List Values
print(patient_record$diagnosis)     # Hypertension
print(patient_record$bp)            # 140/90
print(patient_record$heart_rate)    # NULL (Default if doesn't exist)

This is like checking a patient’s chart — if a piece of information doesn’t exist, R can return a default value (e.g., NULL).

Updating and Adding to a List

You can access items using the $ symbol or double brackets [[ ]]

patient_record$bp         <- "130/85"   # Update blood pressure
patient_record$heart_rate <- 72         # Add new key-value pair, added at the end of the list

print(patient_record)
# $name
# [1] "John Doe"
#
# $age
# [1] 45
#
# $sex
# [1] "Male"
#
# $diagnosis
# [1] "Hypertension"
#
# $bp
# [1] "130/85"
#
# $is_admitted
# [1] TRUE
#
# $heart_rate
# [1] 72

Removing items

patient_record$is_admitted <- NULL   # Remove item by setting to NULL

print(patient_record)
# $name
# [1] "John Doe"
#
# $age
# [1] 45
#
# $sex
# [1] "Male"
#
# $diagnosis
# [1] "Hypertension"
#
# $bp
# [1] "130/85"
#
# $heart_rate
# [1] 72
List Metadata
# Get all labels
names(patient_record)    # [1] "name" "age" "sex" "diagnosis" "bp" "heart_rate"

# Get number of items
length(patient_record)   # [1] 6

In hospital data systems, you might check if certain patient information (like temperature or lab_results) exists before performing calculations or updates.