---
title: "Module 1 Solution — Introduction to R and Data Science"
format:
  html:
    css: "/dark-theme.css"
editor: visual
---
# 🧪 Module 1 Solutions — R Fundamentals and Data Science

This document provides solutions for Module 1 exercises covering R fundamentals, vectors, RStudio workflow, and data science principles applied to clinical programming.

------------------------------------------------------------------------

## ✅ Exercise 1: Working with Vectors (R4DS Ch. 4)

Understanding vectors is fundamental to R programming. Here we create the basic building blocks for clinical data.

```{r}
# Load required packages
library(tidyverse)
library(haven)
library(lubridate)

# Create atomic vectors for clinical data
# Logical vectors for flags
safety_population <- c(TRUE, TRUE, FALSE, TRUE, TRUE)
elderly_flag <- c(FALSE, TRUE, FALSE, TRUE, FALSE)

# Numeric vectors for measurements
age <- c(25, 45, 67, 52, 71)
weight <- c(65.2, 78.5, 85.1, 72.8, 90.3)
height <- c(165, 170, 160, 175, 168)

# Character vectors for IDs and categories
usubjid <- c("001-001", "001-002", "001-003", "001-004", "001-005")
treatment <- c("Placebo", "Drug A", "Drug A", "Placebo", "Drug A")

# Vector operations
bmi <- weight / ((height/100)^2)
age_group <- ifelse(age >= 65, "Elderly", "Adult")

# Display results
cat("Ages:", age, "\n")
cat("BMI:", round(bmi, 1), "\n")
cat("Age Groups:", age_group, "\n")
```

------------------------------------------------------------------------

## ✅ Exercise 2: Create Clinical Dataset with Tibbles

Tibbles are enhanced data frames that provide better printing and stricter subsetting, essential for clinical programming.

```{r}
# Create tibble using vectors from Exercise 1
dm <- tibble(
  USUBJID = usubjid,
  AGE = age,
  WEIGHT = weight,
  HEIGHT = height,
  SEX = c("F", "M", "F", "M", "F"),
  TRT01A = treatment,
  RFSTDTC = c("2024-01-15", "2024-01-16", "2024-01-17", "2024-01-18", "2024-01-19"),
  SAFFL = safety_population,
  BMI = round(bmi, 1),
  AGEGR1 = age_group
)

# Display the dataset
dm

# Explore the dataset structure
glimpse(dm)

# Summary statistics
summary(dm)
```

**Key Learning Points:**
- Tibbles show data types clearly
- Better printing than data.frames
- Stricter subsetting prevents common errors

------------------------------------------------------------------------

## ✅ Exercise 3: RStudio Workflow Practice (R4DS Ch. 6)

Proper workflow practices ensure reproducible and maintainable clinical programming code.

```{r}
# Practice code organization - add comments explaining clinical context
dm <- dm %>%
  mutate(
    # Create elderly flag based on protocol definition (age >= 65)
    ELDERLY = ifelse(AGE >= 65, "Y", "N"),

    # Convert character date to proper Date format for calculations
    RFSTDT = ymd(RFSTDTC),

    # Create BMI categories following clinical guidelines
    BMICAT = case_when(
      BMI < 18.5 ~ "Underweight",
      BMI < 25 ~ "Normal",
      BMI < 30 ~ "Overweight",
      BMI >= 30 ~ "Obese"
    )
  )

# Display the updated dataset
print(dm)
```

**RStudio Best Practices Applied:**
- Clear, descriptive variable names
- Comments explaining clinical context
- Consistent code formatting and indentation
- Logical grouping of related operations

------------------------------------------------------------------------

## ✅ Exercise 4 & 5: Project Organization and Data Summarization

Understanding project structure and creating summaries are essential for clinical programming workflows.

```{r}
# Project organization demonstration
cat("Current working directory:", getwd(), "\n")

cat("\nRecommended clinical project structure:\n")
cat("my_clinical_study/\n")
cat("├── my_clinical_study.Rproj\n")
cat("├── data/\n")
cat("│   ├── raw/           # Original data files\n")
cat("│   ├── sdtm/          # SDTM datasets\n")
cat("│   └── adam/          # ADAM datasets\n")
cat("├── programs/\n")
cat("│   ├── sdtm/          # SDTM creation programs\n")
cat("│   ├── adam/          # ADAM creation programs\n")
cat("│   └── tlf/           # Tables, listings, figures programs\n")
cat("└── outputs/           # Generated outputs\n")
```

```{r}
# Create safety population summary following good practices
safety_summary <- dm %>%
  filter(SAFFL == TRUE) %>%               # Keep only safety population
  select(USUBJID, AGE, SEX, TRT01A, BMICAT) %>%  # Select key variables
  arrange(AGE)                            # Sort by age

print(safety_summary)
```

```{r}
# Data summarization examples
# 1. BMI category counts
bmi_summary <- dm %>%
  count(BMICAT, name = "n_subjects")

# 2. Mean age by treatment
age_by_treatment <- dm %>%
  group_by(TRT01A) %>%
  summarise(
    n = n(),
    mean_age = mean(AGE),
    sd_age = sd(AGE)
  )

# 3. Elderly subjects count
elderly_summary <- dm %>%
  count(ELDERLY)

print("BMI Category Summary:")
print(bmi_summary)

print("Age by Treatment:")
print(age_by_treatment)

print("Elderly Summary:")
print(elderly_summary)
```

------------------------------------------------------------------------

## ✅ Exercises 6 & 7: Help System and String Manipulation

Learning to get help and manipulate strings are crucial skills for clinical programming.

```{r}
# Getting help examples
cat("R Help System Commands:\n")
cat("?mean        # Help for specific function\n")
cat("??regression # Search for functions\n")
cat("example(mean) # See function examples\n")
cat("args(lm)     # View function arguments\n\n")

# String manipulation for clinical data
dm <- dm %>%
  mutate(
    # Extract site number from USUBJID (part before the dash)
    SITE = str_extract(USUBJID, "\\d{3}"),  # Extracts first 3 digits

    # Create formatted subject label
    SUBJ_LABEL = paste0("Subject ", USUBJID, " (Age: ", AGE, ")")
  )

print(dm)
```

```{r}
# Example calculations for AI assistance practice
young_flag <- ifelse(dm$AGE < 30, "Y", "N")
treatment_weeks <- 12
total_days <- treatment_weeks * 7

cat("Example calculations:\n")
cat("Young subjects (< 30 years):", sum(young_flag == "Y"), "\n")
cat("Treatment duration:", treatment_weeks, "weeks =", total_days, "days\n")
```

------------------------------------------------------------------------

## ✅ Final Summary Report

Creating comprehensive summaries is essential for clinical data review.

```{r}
# Create a clinical summary report
cat("=== DEMOGRAPHICS SUMMARY ===\n")
cat("Total subjects:", nrow(dm), "\n")
cat("Age range:", min(dm$AGE), "to", max(dm$AGE), "years\n")
cat("Female subjects:", sum(dm$SEX == "F"), "\n")
cat("Male subjects:", sum(dm$SEX == "M"), "\n")
cat("Elderly subjects (65+):", sum(dm$ELDERLY == "Y"), "\n")
cat("Safety population:", sum(dm$SAFFL == TRUE), "\n")

# Treatment distribution
cat("\nTreatment Distribution:\n")
print(table(dm$TRT01A))

# BMI category distribution
cat("\nBMI Category Distribution:\n")
print(table(dm$BMICAT))
```

------------------------------------------------------------------------

## 🎯 Module 1 Learning Summary

You have successfully completed all R4DS Chapter integrations:

**✅ Chapter 1**: Understanding the data science process in clinical context
**✅ Chapter 4**: Working with vectors as R's fundamental data structures
**✅ Chapter 6**: RStudio workflow best practices for clinical programming
**✅ Chapter 8**: Script organization and project management for reproducibility

### Key Skills Developed:
- Vector creation and manipulation for clinical data
- Tibble creation and data structure understanding
- RStudio interface navigation and productivity features
- Code organization and documentation best practices
- Project structure for regulatory compliance
- Data summarization and reporting techniques

### Clinical Programming Applications:
- CDISC-compliant variable naming and structure
- Regulatory-ready code documentation
- Reproducible analysis workflows
- Efficient data manipulation patterns

🚀 **Ready for Module 2**: Data Manipulation with dplyr's five key verbs!
