Section A – Writing Basic Functions

Problem 1: Add Blood Sugar Readings

add_glucose <- function(a, b) {
  return(a + b)
}

# Test the function
add_glucose(110, 125)
## [1] 235

Problem 2: Calculate BMI

calculate_BMI <- function(weight, height) {
  bmi <- weight / (height^2)
  return(bmi)
}

# Test with weight = 72 kg, height = 1.68 m
calculate_BMI(72, 1.68)
## [1] 25.5102

Problem 3: Multiply Experimental Readings

enzyme_product <- function(a, b, c) {
  return(a * b * c)
}

# Test with sample absorbance values
enzyme_product(0.45, 0.62, 0.38)
## [1] 0.10602

Problem 4: Add Default Value Parameter

assay_ratio <- function(treatment, control = 100) {
  return(treatment / control)
}

# Run WITH specifying control
cat("With control = 80:\n")
## With control = 80:
assay_ratio(150, 80)
## [1] 1.875
# Run WITHOUT specifying control (uses default 100)
cat("With default control:\n")
## With default control:
assay_ratio(150)
## [1] 1.5

Problem 5: Welcome Message for New Students

welcome_student <- function(name) {
  cat("Welcome to the R for Biostatistics course,", name, "!\n")
}

# Test the function
welcome_student("Aisha")
## Welcome to the R for Biostatistics course, Aisha !
welcome_student("Rahman")
## Welcome to the R for Biostatistics course, Rahman !

Section B – Functions with Statistics and Loops

Problem 6: Summary Statistics for Blood Pressure

bp_summary <- function(x) {
  result <- list(
    Mean   = mean(x),
    Median = median(x),
    SD     = sd(x),
    Min    = min(x),
    Max    = max(x)
  )
  return(result)
}

# Test with given data
bp_data <- c(120, 135, 140, 150, 125, 138, 145, 132, 128, 134)
bp_summary(bp_data)
## $Mean
## [1] 134.7
## 
## $Median
## [1] 134.5
## 
## $SD
## [1] 9.080504
## 
## $Min
## [1] 120
## 
## $Max
## [1] 150

Problem 7: Calculate Total Cholesterol (Using a For Loop)

total_cholesterol <- function(x) {
  total <- 0
  for (val in x) {
    total <- total + val
  }
  return(total)
}

# Test with given cholesterol values
chol_values <- c(180, 190, 200, 210, 195)
total_cholesterol(chol_values)
## [1] 975

Problem 8: Compute the Mean Using a Loop

my_mean <- function(x) {
  total <- 0
  for (val in x) {
    total <- total + val
  }
  result <- total / length(x)
  return(result)
}

# Test with cholesterol values
my_mean(chol_values)
## [1] 195
# Verify against built-in mean()
cat("Built-in mean():", mean(chol_values), "\n")
## Built-in mean(): 195

Section C – Loops and Iteration

Problem 9: Generate Multiple Messages

for (week in 1:4) {
  cat("Submit lab results for Week", week, "\n")
}
## Submit lab results for Week 1 
## Submit lab results for Week 2 
## Submit lab results for Week 3 
## Submit lab results for Week 4

Problem 10: Annual Record Tracker

for (year in 2010:2025) {
  cat("Generating report for year:", year, "\n")
}
## Generating report for year: 2010 
## Generating report for year: 2011 
## Generating report for year: 2012 
## Generating report for year: 2013 
## Generating report for year: 2014 
## Generating report for year: 2015 
## Generating report for year: 2016 
## Generating report for year: 2017 
## Generating report for year: 2018 
## Generating report for year: 2019 
## Generating report for year: 2020 
## Generating report for year: 2021 
## Generating report for year: 2022 
## Generating report for year: 2023 
## Generating report for year: 2024 
## Generating report for year: 2025

Section D – Data Import, Cleaning, and Export

Problem 11: Import Clinical Data

# First, we create the CSV file so this note is self-contained
clinical_csv <- "Patient_ID,Age,BMI,Glucose,BP
P001,45,24.5,95,120
P002,50,30.1,130,140
P003,38,28.0,110,130
P004,60,33.4,160,155
P005,55,27.2,145,148
P006,42,25.9,102,118
P007,47,31.0,120,135
P008,63,29.8,170,160"

writeLines(clinical_csv, "clinical_data.csv")

# Now import and inspect
clinical_data <- read.csv("clinical_data.csv", stringsAsFactors = FALSE)
str(clinical_data)
## 'data.frame':    8 obs. of  5 variables:
##  $ Patient_ID: chr  "P001" "P002" "P003" "P004" ...
##  $ Age       : int  45 50 38 60 55 42 47 63
##  $ BMI       : num  24.5 30.1 28 33.4 27.2 25.9 31 29.8
##  $ Glucose   : int  95 130 110 160 145 102 120 170
##  $ BP        : int  120 140 130 155 148 118 135 160

Problem 12: Add a Derived Column

# Risk_Index = (BMI * Glucose) / BP
clinical_data$Risk_Index <- (clinical_data$BMI * clinical_data$Glucose) / clinical_data$BP
print(clinical_data)
##   Patient_ID Age  BMI Glucose  BP Risk_Index
## 1       P001  45 24.5      95 120   19.39583
## 2       P002  50 30.1     130 140   27.95000
## 3       P003  38 28.0     110 130   23.69231
## 4       P004  60 33.4     160 155   34.47742
## 5       P005  55 27.2     145 148   26.64865
## 6       P006  42 25.9     102 118   22.38814
## 7       P007  47 31.0     120 135   27.55556
## 8       P008  63 29.8     170 160   31.66250

Problem 13: Write Processed Data to a File

write.csv(clinical_data, "cleaned_clinical_data.csv", row.names = FALSE)
cat("File 'cleaned_clinical_data.csv' has been saved successfully.\n")
## File 'cleaned_clinical_data.csv' has been saved successfully.
# Verify by reading it back
verify <- read.csv("cleaned_clinical_data.csv")
head(verify)
##   Patient_ID Age  BMI Glucose  BP Risk_Index
## 1       P001  45 24.5      95 120   19.39583
## 2       P002  50 30.1     130 140   27.95000
## 3       P003  38 28.0     110 130   23.69231
## 4       P004  60 33.4     160 155   34.47742
## 5       P005  55 27.2     145 148   26.64865
## 6       P006  42 25.9     102 118   22.38814

Section E – Advanced Functions and Real-World Data

Problem 14: Gene Expression Summary

gene_summary <- function(x) {
  avg <- mean(x)
  med <- median(x)
  
  if (avg > 500) {
    category <- "High Expression"
  } else {
    category <- "Low Expression"
  }
  
  result <- list(
    Mean = avg,
    Median = med,
    Expression_Category = category
  )
  return(result)
}

# Test with given gene expression values
gene_expr <- c(350, 420, 580, 700, 450, 800, 900, 650, 300, 500)
gene_summary(gene_expr)
## $Mean
## [1] 565
## 
## $Median
## [1] 540
## 
## $Expression_Category
## [1] "High Expression"

Problem 15: Automated Global Health Data Cleaner

# Attempt to download and clean the World Bank GDP dataset
gdp_url <- "https://databank.worldbank.org/data/download/GDP.csv"


tryCatch({
  # 1. Read the dataset (skip metadata rows if needed)
  gdp_raw <- read.csv(gdp_url, skip = 3, stringsAsFactors = FALSE, 
                       na.strings = c("", "..", "NA"))
  
  # 2. Select only the first 5 columns
  gdp_raw <- gdp_raw[, 1:5]
  
  # 3. Rename columns
  colnames(gdp_raw) <- c("Short_Name", "Ranking", "Long_Name", "GDP", "Other")
  
  # Remove rows where Ranking is not numeric (header/footer artifacts)
  gdp_clean <- gdp_raw[!is.na(gdp_clean_num <- suppressWarnings(as.numeric(gdp_raw$Ranking))), ]
  gdp_clean$Ranking <- as.numeric(gdp_clean$Ranking)
  
  # 4. Convert GDP from text to numeric by removing commas
  gdp_clean$GDP <- as.numeric(gsub(",", "", gdp_clean$GDP))
  
  # Remove rows with NA GDP
  gdp_clean <- gdp_clean[!is.na(gdp_clean$GDP), ]
  
  # 5. Compute mean and total GDP
  cat("Mean GDP:", mean(gdp_clean$GDP), "\n")
  cat("Total GDP:", sum(gdp_clean$GDP), "\n")
  cat("Number of countries:", nrow(gdp_clean), "\n\n")
  
  # Show first few rows
  cat("First 6 rows of cleaned data:\n")
  print(head(gdp_clean))
  
  # 6. Save cleaned data
  write.csv(gdp_clean, "Cleaned_GDP.csv", row.names = FALSE)
  cat("\nFile 'Cleaned_GDP.csv' saved successfully.\n")
  
}, error = function(e) {
  cat("Note: Could not download the World Bank GDP dataset.\n")
  cat("Error:", conditionMessage(e), "\n")
})
## Note: Could not download the World Bank GDP dataset.
## Error: cannot open the connection to 'https://databank.worldbank.org/data/download/GDP.csv'