0% found this document useful (0 votes)
12 views34 pages

R Lab Program

The document is a comprehensive guide for R programming exercises tailored for BCA Semester VI students at the University of Madras. It covers various topics including data types, reading and writing data, database interactions, date manipulation, factors, subsetting, character manipulation, data aggregation, reshaping data, and statistical analysis techniques such as t-tests and regression. Each exercise includes code snippets and explanations to facilitate learning and application of R programming concepts.

Uploaded by

gchristo2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views34 pages

R Lab Program

The document is a comprehensive guide for R programming exercises tailored for BCA Semester VI students at the University of Madras. It covers various topics including data types, reading and writing data, database interactions, date manipulation, factors, subsetting, character manipulation, data aggregation, reshaping data, and statistical analysis techniques such as t-tests and regression. Each exercise includes code snippets and explanations to facilitate learning and application of R programming concepts.

Uploaded by

gchristo2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

##############################################

##################################

# R PROGRAMMING PRACTICAL - BCA SEMESTER VI

# University of Madras - Complete Exercise Solutions

# Course Code: 320C61

##############################################
##################################

##############################################
##################################

# EXERCISE 1: DATA IN R

##############################################
##################################

cat("\n=== EXERCISE 1: DATA IN R ===\n")

# Basic data types

num_var <- 42

char_var <- "Hello R"

logical_var <- TRUE

complex_var <- 3 + 4i

# Vectors

numeric_vector <- c(1, 2, 3, 4, 5)

character_vector <- c("apple", "banana", "cherry")

logical_vector <- c(TRUE, FALSE, TRUE)

# Matrices

my_matrix <- matrix(1:9, nrow = 3, ncol = 3)


print("Matrix:")

print(my_matrix)

# Arrays

my_array <- array(1:24, dim = c(3, 4, 2))

# Data Frames

student_data <- [Link](

Name = c("John", "Alice", "Bob", "Diana"),

Age = c(20, 22, 21, 23),

Grade = c("A", "B", "A", "A"),

Score = c(85, 78, 92, 88)

print("Student Data Frame:")

print(student_data)

# Lists

my_list <- list(

numbers = c(1, 2, 3),

name = "R Programming",

matrix = matrix(1:4, nrow = 2),

dataframe = student_data

##############################################
##################################

# EXERCISE 2: READING AND WRITING DATA


##############################################
##################################

cat("\n=== EXERCISE 2: READING AND WRITING DATA ===\n")

# Writing CSV file

[Link](student_data, "student_data.csv", [Link] = FALSE)

cat("CSV file created: student_data.csv\n")

# Reading CSV file

read_data <- [Link]("student_data.csv")

print("Data read from CSV:")

print(read_data)

# Writing to text file

[Link](student_data, "student_data.txt", sep = "\t", [Link] = FALSE)

# Reading from text file

text_data <- [Link]("student_data.txt", header = TRUE, sep = "\t")

# Writing and reading RDS (R Data Serialization)

saveRDS(student_data, "student_data.rds")

rds_data <- readRDS("student_data.rds")

# Save and load R workspace

save(student_data, my_matrix, file = "[Link]")

# load("[Link]")
##############################################
##################################

# EXERCISE 3: R AND DATABASES

##############################################
##################################

cat("\n=== EXERCISE 3: R AND DATABASES ===\n")

# Using SQLite database (built-in)

if(require(RSQLite)) {

# Create connection

con <- dbConnect(RSQLite::SQLite(), "student_db.sqlite")

# Write data to database

dbWriteTable(con, "students", student_data, overwrite = TRUE)

# Query database

query_result <- dbGetQuery(con, "SELECT * FROM students WHERE Age >


21")

print("Database Query Result:")

print(query_result)

# Close connection

dbDisconnect(con)

} else {

cat("Install RSQLite package: [Link]('RSQLite')\n")

}
##############################################
##################################

# EXERCISE 4: DATES

##############################################
##################################

cat("\n=== EXERCISE 4: DATES ===\n")

# Current date and time

current_date <- [Link]()

current_time <- [Link]()

cat("Current Date:", [Link](current_date), "\n")

cat("Current Time:", [Link](current_time), "\n")

# Creating dates

my_date <- [Link]("2024-01-15")

formatted_date <- format(my_date, "%B %d, %Y")

cat("Formatted Date:", formatted_date, "\n")

# Date arithmetic

future_date <- my_date + 30

date_diff <- [Link](difftime(future_date, my_date, units = "days"))

cat("Days difference:", date_diff, "\n")

# Working with POSIXct

timestamp <- [Link]("2024-01-15 14:30:00")

cat("Timestamp:", [Link](timestamp), "\n")


# Extract components

year <- format(my_date, "%Y")

month <- format(my_date, "%m")

day <- format(my_date, "%d")

##############################################
##################################

# EXERCISE 5: FACTORS

##############################################
##################################

cat("\n=== EXERCISE 5: FACTORS ===\n")

# Creating factors

gender <- factor(c("Male", "Female", "Male", "Female", "Male"))

print("Gender Factor:")

print(gender)

# Factor levels

education <- factor(c("High School", "Bachelor", "Master", "Bachelor"),

levels = c("High School", "Bachelor", "Master", "PhD"),

ordered = TRUE)

print("Ordered Education Factor:")

print(education)

# Factor manipulation

levels(gender)

nlevels(gender)
table(gender)

# Converting factors

[Link](education)

[Link](gender)

# Relevel factors

gender_releveled <- relevel(gender, ref = "Female")

##############################################
##################################

# EXERCISE 6: SUBSETTING

##############################################
##################################

cat("\n=== EXERCISE 6: SUBSETTING ===\n")

# Vector subsetting

vec <- c(10, 20, 30, 40, 50)

vec[1] # First element

vec[c(1, 3, 5)] # Multiple elements

vec[-2] # Exclude second element

vec[vec > 25] # Conditional subsetting

# Matrix subsetting

mat <- matrix(1:12, nrow = 3, ncol = 4)

mat[2, 3] # Element at row 2, col 3

mat[2, ] # Entire row 2


mat[, 3] # Entire column 3

mat[1:2, 2:4] # Submatrix

# Data frame subsetting

df <- [Link](

ID = 1:5,

Name = c("A", "B", "C", "D", "E"),

Score = c(85, 90, 78, 92, 88)

df[df$Score > 85, ] # Rows where Score > 85

df[df$Score > 85, "Name"] # Names where Score > 85

subset(df, Score > 85) # Using subset function

df[df$Score > 85 & df$ID < 5, ] # Multiple conditions

##############################################
##################################

# EXERCISE 7: CHARACTER MANIPULATION

##############################################
##################################

cat("\n=== EXERCISE 7: CHARACTER MANIPULATION ===\n")

# String operations

text <- "R Programming"

tolower(text)

toupper(text)

nchar(text)
# String concatenation

paste("Hello", "World")

paste0("R", "Programming") # No separator

# Substring

substr(text, 1, 4)

substring(text, 3, 8)

# String replacement

gsub("Programming", "Language", text)

sub("R", "Python", text)

# String splitting

strsplit("apple,banana,cherry", ",")

# Pattern matching

grep("gram", text)

grepl("prog", text, [Link] = TRUE)

# String formatting

sprintf("Score: %.2f", 85.5678)

##############################################
##################################

# EXERCISE 8: DATA AGGREGATION


##############################################
##################################

cat("\n=== EXERCISE 8: DATA AGGREGATION ===\n")

# Sample data

sales_data <- [Link](

Region = c("North", "South", "North", "East", "South", "East"),

Product = c("A", "B", "A", "B", "A", "B"),

Sales = c(100, 150, 120, 180, 140, 160)

# Aggregate function

agg_result <- aggregate(Sales ~ Region, data = sales_data, FUN = sum)

print("Aggregated Sales by Region:")

print(agg_result)

# Multiple aggregations

agg_multi <- aggregate(Sales ~ Region + Product, data = sales_data, FUN =


mean)

print("Average Sales by Region and Product:")

print(agg_multi)

# Using tapply

tapply(sales_data$Sales, sales_data$Region, sum)

# Using by

by(sales_data$Sales, sales_data$Region, summary)


##############################################
##################################

# EXERCISE 9: RESHAPING DATA BASICS

##############################################
##################################

cat("\n=== EXERCISE 9: RESHAPING DATA BASICS ===\n")

# Wide to long format

wide_data <- [Link](

ID = 1:3,

Year2021 = c(100, 110, 120),

Year2022 = c(105, 115, 125),

Year2023 = c(110, 120, 130)

long_data <- reshape(wide_data,

varying = c("Year2021", "Year2022", "Year2023"),

[Link] = "Value",

timevar = "Year",

times = c(2021, 2022, 2023),

direction = "long")

print("Long Format Data:")

print(long_data)

# Long to wide format


wide_back <- reshape(long_data,

timevar = "Year",

idvar = "ID",

direction = "wide")

# Using stack and unstack

stacked <- stack(wide_data[, -1])

unstacked <- unstack(stacked)

##############################################
##################################

# EXERCISE 10: THE R ENVIRONMENT

##############################################
##################################

cat("\n=== EXERCISE 10: THE R ENVIRONMENT ===\n")

# List objects in workspace

ls()

# Remove objects

temp_var <- 10

rm(temp_var)

# Get working directory

getwd()

# Set working directory


# setwd("/path/to/directory")

# Search path

search()

# Installed packages

[Link]()[1:5, c("Package", "Version")]

# Load package

# library(package_name)

# Session information

sessionInfo()

# Memory usage

[Link](student_data)

# Get help

# ?mean

# help(mean)

##############################################
##################################

# EXERCISE 11: PROBABILITY AND DISTRIBUTIONS

##############################################
##################################

cat("\n=== EXERCISE 11: PROBABILITY AND DISTRIBUTIONS ===\n")


# Normal distribution

x <- seq(-4, 4, length = 100)

y <- dnorm(x, mean = 0, sd = 1)

plot(x, y, type = "l", main = "Normal Distribution",

xlab = "x", ylab = "Density")

# Probability calculations

pnorm(1.96) # P(Z <= 1.96)

qnorm(0.975) # Z-value for 97.5% probability

rnorm(10, mean = 100, sd = 15) # Random normal values

# Binomial distribution

dbinom(3, size = 10, prob = 0.5) # P(X = 3)

pbinom(3, size = 10, prob = 0.5) # P(X <= 3)

rbinom(10, size = 10, prob = 0.5) # Random binomial values

# Poisson distribution

dpois(5, lambda = 3)

ppois(5, lambda = 3)

# Uniform distribution

runif(10, min = 0, max = 1)

##############################################
##################################

# EXERCISE 12: DESCRIPTIVE STATISTICS AND GRAPHICS


##############################################
##################################

cat("\n=== EXERCISE 12: DESCRIPTIVE STATISTICS AND GRAPHICS ===\n")

# Sample data

scores <- c(85, 78, 92, 88, 76, 95, 82, 90, 87, 91)

# Measures of central tendency

mean_score <- mean(scores)

median_score <- median(scores)

# mode (no built-in function)

# Measures of dispersion

var_score <- var(scores)

sd_score <- sd(scores)

range_score <- range(scores)

iqr_score <- IQR(scores)

cat("Mean:", mean_score, "\n")

cat("Median:", median_score, "\n")

cat("SD:", sd_score, "\n")

# Summary statistics

summary(scores)

# Graphics

par(mfrow = c(2, 2)) # 2x2 plot layout


# Histogram

hist(scores, main = "Histogram of Scores", xlab = "Scores", col = "lightblue")

# Boxplot

boxplot(scores, main = "Boxplot of Scores", ylab = "Scores", col =


"lightgreen")

# Scatter plot

x <- 1:10

plot(x, scores, main = "Scatter Plot", xlab = "Student ID",

ylab = "Score", pch = 19, col = "red")

# Bar plot

categories <- c("A", "B", "C", "D")

counts <- c(15, 20, 18, 12)

barplot(counts, [Link] = categories, main = "Bar Plot",

xlab = "Category", ylab = "Count", col = "orange")

par(mfrow = c(1, 1)) # Reset plot layout

##############################################
##################################

# EXERCISE 13: ONE- AND TWO-SAMPLE TESTS

##############################################
##################################

cat("\n=== EXERCISE 13: ONE- AND TWO-SAMPLE TESTS ===\n")


# One-sample t-test

sample_data <- c(23, 25, 27, 29, 31, 28, 26, 30, 24, 28)

t_test_one <- [Link](sample_data, mu = 25)

print("One-Sample t-test:")

print(t_test_one)

# Two-sample t-test (independent)

group1 <- c(23, 25, 27, 29, 31)

group2 <- c(20, 22, 24, 26, 28)

t_test_two <- [Link](group1, group2)

print("Two-Sample t-test:")

print(t_test_two)

# Paired t-test

before <- c(120, 135, 128, 140, 132)

after <- c(115, 130, 125, 135, 128)

t_test_paired <- [Link](before, after, paired = TRUE)

print("Paired t-test:")

print(t_test_paired)

# Wilcoxon test (non-parametric)

wilcox_test <- [Link](group1, group2)

print("Wilcoxon Test:")

print(wilcox_test)

##############################################
##################################
# EXERCISE 14: REGRESSION AND CORRELATION

##############################################
##################################

cat("\n=== EXERCISE 14: REGRESSION AND CORRELATION ===\n")

# Sample data

hours_studied <- c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

exam_scores <- c(55, 60, 65, 70, 75, 80, 85, 88, 92, 95)

# Correlation

cor_result <- cor(hours_studied, exam_scores)

cat("Correlation coefficient:", cor_result, "\n")

# Correlation test

cor_test <- [Link](hours_studied, exam_scores)

print(cor_test)

# Simple linear regression

model <- lm(exam_scores ~ hours_studied)

print("Linear Regression Model:")

print(summary(model))

# Plotting regression

plot(hours_studied, exam_scores, main = "Regression Analysis",

xlab = "Hours Studied", ylab = "Exam Scores", pch = 19)

abline(model, col = "red", lwd = 2)


# Predictions

new_data <- [Link](hours_studied = c(5.5, 8.5))

predictions <- predict(model, newdata = new_data)

cat("Predictions:", predictions, "\n")

##############################################
##################################

# EXERCISE 15: ANALYSIS OF VARIANCE AND KRUSKAL-WALLIS TEST

##############################################
##################################

cat("\n=== EXERCISE 15: ANOVA AND KRUSKAL-WALLIS TEST ===\n")

# Sample data for ANOVA

group_A <- c(23, 25, 27, 29, 31)

group_B <- c(28, 30, 32, 34, 36)

group_C <- c(20, 22, 24, 26, 28)

# Create data frame

anova_data <- [Link](

value = c(group_A, group_B, group_C),

group = factor(rep(c("A", "B", "C"), each = 5))

# One-way ANOVA

anova_result <- aov(value ~ group, data = anova_data)

print("ANOVA Results:")

print(summary(anova_result))
# Post-hoc test (Tukey HSD)

tukey_result <- TukeyHSD(anova_result)

print("Tukey HSD:")

print(tukey_result)

# Kruskal-Wallis test (non-parametric alternative to ANOVA)

kruskal_result <- [Link](value ~ group, data = anova_data)

print("Kruskal-Wallis Test:")

print(kruskal_result)

# Boxplot for visualization

boxplot(value ~ group, data = anova_data,

main = "Comparison of Groups",

xlab = "Group", ylab = "Value", col = c("red", "green", "blue"))

##############################################
##################################

# EXERCISE 16: TABULAR DATA

##############################################
##################################

cat("\n=== EXERCISE 16: TABULAR DATA ===\n")

# Creating contingency tables

survey_data <- [Link](

Gender = c("M", "F", "M", "F", "M", "F", "M", "F"),

Preference = c("A", "B", "A", "A", "B", "B", "A", "B")


)

# Frequency table

freq_table <- table(survey_data$Gender, survey_data$Preference)

print("Frequency Table:")

print(freq_table)

# Proportions

prop_table <- [Link](freq_table)

print("Proportion Table:")

print(prop_table)

# Row and column proportions

[Link](freq_table, 1) # Row proportions

[Link](freq_table, 2) # Column proportions

# Chi-square test

chi_test <- [Link](freq_table)

print("Chi-Square Test:")

print(chi_test)

# Marginal tables

[Link](freq_table, 1) # Row totals

[Link](freq_table, 2) # Column totals

# Add margins

addmargins(freq_table)
##############################################
##################################

# EXERCISE 17: POWER AND COMPUTATION OF SAMPLE SIZE

##############################################
##################################

cat("\n=== EXERCISE 17: POWER AND SAMPLE SIZE ===\n")

# Power calculation for t-test

power_result <- [Link](

n = NULL, # Sample size to be calculated

delta = 0.5, # Effect size

sd = 1, # Standard deviation

[Link] = 0.05, # Significance level

power = 0.80, # Desired power

type = "[Link]"

print("Power Analysis for t-test:")

print(power_result)

# Sample size for proportion test

power_prop <- [Link](

n = NULL,

p1 = 0.65,

p2 = 0.75,

[Link] = 0.05,

power = 0.80
)

print("Sample Size for Proportion Test:")

print(power_prop)

# Power for ANOVA

power_anova <- [Link](

groups = 3,

n = NULL,

[Link] = 1,

[Link] = 3,

[Link] = 0.05,

power = 0.80

print("Power Analysis for ANOVA:")

print(power_anova)

##############################################
##################################

# EXERCISE 18: ADVANCED DATA HANDLING

##############################################
##################################

cat("\n=== EXERCISE 18: ADVANCED DATA HANDLING ===\n")

# Merging data frames

df1 <- [Link](ID = 1:4, Name = c("A", "B", "C", "D"))

df2 <- [Link](ID = c(2, 3, 4, 5), Score = c(85, 90, 78, 92))
# Inner join

inner_merge <- merge(df1, df2, by = "ID")

print("Inner Merge:")

print(inner_merge)

# Outer join

outer_merge <- merge(df1, df2, by = "ID", all = TRUE)

print("Outer Merge:")

print(outer_merge)

# Apply family functions

data_matrix <- matrix(1:12, nrow = 3)

# apply on matrix

row_sums <- apply(data_matrix, 1, sum)

col_means <- apply(data_matrix, 2, mean)

# lapply (returns list)

my_list <- list(a = 1:5, b = 6:10, c = 11:15)

list_means <- lapply(my_list, mean)

# sapply (simplified output)

vector_means <- sapply(my_list, mean)

# mapply (multivariate)

mapply_result <- mapply(sum, 1:5, 6:10, 11:15)


# Data cleaning

messy_data <- [Link](

ID = c(1, 2, NA, 4, 5),

Value = c(10, NA, 30, 40, 50)

# Remove NA rows

clean_data <- [Link](messy_data)

# Replace NA with mean

messy_data$Value[[Link](messy_data$Value)] <- mean(messy_data$Value,


[Link] = TRUE)

##############################################
##################################

# EXERCISE 19: MULTIPLE REGRESSION

##############################################
##################################

cat("\n=== EXERCISE 19: MULTIPLE REGRESSION ===\n")

# Sample data

multi_data <- [Link](

Sales = c(150, 180, 200, 220, 250, 280, 300, 320, 350, 380),

Advertising = c(10, 12, 15, 18, 20, 22, 25, 28, 30, 35),

Price = c(50, 48, 45, 42, 40, 38, 35, 32, 30, 28),

Competition = c(5, 6, 7, 8, 9, 10, 11, 12, 13, 14)

)
# Multiple regression model

multi_model <- lm(Sales ~ Advertising + Price + Competition, data =


multi_data)

print("Multiple Regression Summary:")

print(summary(multi_model))

# Coefficients

coef(multi_model)

# Confidence intervals

confint(multi_model)

# Predictions

new_obs <- [Link](Advertising = 20, Price = 40, Competition = 10)

predict(multi_model, newdata = new_obs, interval = "prediction")

# Model diagnostics

par(mfrow = c(2, 2))

plot(multi_model)

par(mfrow = c(1, 1))

# Variance Inflation Factor (VIF) - check for multicollinearity

# if(require(car)) {

# vif(multi_model)

#}
##############################################
##################################

# EXERCISE 20: LINEAR MODELS

##############################################
##################################

cat("\n=== EXERCISE 20: LINEAR MODELS ===\n")

# ANOVA as linear model

plant_data <- [Link](

Growth = c(20, 22, 19, 25, 27, 26, 30, 32, 31, 28, 29, 27),

Fertilizer = factor(rep(c("A", "B", "C"), each = 4))

# Linear model for ANOVA

lm_anova <- lm(Growth ~ Fertilizer, data = plant_data)

print("Linear Model (ANOVA):")

print(summary(lm_anova))

print(anova(lm_anova))

# ANCOVA (Analysis of Covariance)

ancova_data <- [Link](

Response = c(15, 18, 20, 22, 25, 28, 30, 32, 35, 38),

Group = factor(rep(c("Control", "Treatment"), each = 5)),

Covariate = c(10, 12, 14, 16, 18, 11, 13, 15, 17, 19)

ancova_model <- lm(Response ~ Group + Covariate, data = ancova_data)


print("ANCOVA Model:")

print(summary(ancova_model))

# Polynomial regression

x_poly <- 1:20

y_poly <- 3 + 2*x_poly + 0.5*x_poly^2 + rnorm(20, 0, 5)

poly_model <- lm(y_poly ~ poly(x_poly, 2))

print("Polynomial Regression:")

print(summary(poly_model))

##############################################
##################################

# EXERCISE 21: LOGISTIC REGRESSION

##############################################
##################################

cat("\n=== EXERCISE 21: LOGISTIC REGRESSION ===\n")

# Binary outcome data

logit_data <- [Link](

Age = c(22, 25, 28, 32, 35, 40, 45, 50, 55, 60),

Income = c(30, 35, 40, 45, 50, 55, 60, 65, 70, 75),

Purchase = c(0, 0, 0, 1, 0, 1, 1, 1, 1, 1)

# Logistic regression model

logit_model <- glm(Purchase ~ Age + Income,

data = logit_data,
family = binomial(link = "logit"))

print("Logistic Regression Summary:")

print(summary(logit_model))

# Odds ratios

exp(coef(logit_model))

# Predictions (probabilities)

predicted_probs <- predict(logit_model, type = "response")

cat("Predicted Probabilities:\n")

print(predicted_probs)

# Classification

predicted_class <- ifelse(predicted_probs > 0.5, 1, 0)

# Confusion matrix

table(Predicted = predicted_class, Actual = logit_data$Purchase)

# Model fit statistics

# if(require(pscl)) {

# pR2(logit_model)

#}

##############################################
##################################

# EXERCISE 22: SURVIVAL ANALYSIS


##############################################
##################################

cat("\n=== EXERCISE 22: SURVIVAL ANALYSIS ===\n")

if(require(survival)) {

# Sample survival data

time <- c(5, 8, 12, 15, 20, 24, 30, 35, 40, 45)

status <- c(1, 1, 0, 1, 1, 0, 1, 0, 1, 1) # 1 = event occurred, 0 = censored

group <- factor(c(rep("A", 5), rep("B", 5)))

# Create survival object

surv_obj <- Surv(time, status)

# Kaplan-Meier survival curve

km_fit <- survfit(surv_obj ~ 1)

print("Kaplan-Meier Survival:")

print(km_fit)

# Plot survival curve

plot(km_fit, main = "Kaplan-Meier Survival Curve",

xlab = "Time", ylab = "Survival Probability",

[Link] = TRUE)

# Compare survival between groups

km_groups <- survfit(surv_obj ~ group)

plot(km_groups, col = c("red", "blue"),

main = "Survival by Group",


xlab = "Time", ylab = "Survival Probability")

legend("topright", legend = c("Group A", "Group B"),

col = c("red", "blue"), lty = 1)

# Log-rank test

logrank_test <- survdiff(surv_obj ~ group)

print("Log-rank Test:")

print(logrank_test)

# Cox proportional hazards model

age <- c(45, 50, 55, 60, 65, 48, 52, 58, 62, 68)

cox_model <- coxph(surv_obj ~ group + age)

print("Cox Proportional Hazards Model:")

print(summary(cox_model))

} else {

cat("Install survival package: [Link]('survival')\n")

##############################################
##################################

# EXERCISE 23: RATES AND POISSON REGRESSION

##############################################
##################################

cat("\n=== EXERCISE 23: RATES AND POISSON REGRESSION ===\n")

# Count data

poisson_data <- [Link](


Cases = c(2, 3, 5, 7, 9, 12, 15, 18, 20, 25),

Treatment = factor(rep(c("A", "B"), each = 5)),

Age = c(25, 30, 35, 40, 45, 28, 32, 38, 42, 48)

# Poisson regression

poisson_model <- glm(Cases ~ Treatment + Age,

data = poisson_data,

family = poisson(link = "log"))

print("Poisson Regression Summary:")

print(summary(poisson_model))

# Rate ratios (exponentiated coefficients)

cat("Rate Ratios:\n")

print(exp(coef(poisson_model)))

# Predictions

predict(poisson_model, type = "response")

# Goodness of fit

deviance(poisson_model)

pchisq(deviance(poisson_model), [Link](poisson_model), [Link] =


FALSE)

# Overdispersion check

# Check if residual deviance >> degrees of freedom


cat("Dispersion parameter:",
deviance(poisson_model)/[Link](poisson_model), "\n")

# If overdispersed, use quasi-Poisson

quasi_poisson_model <- glm(Cases ~ Treatment + Age,

data = poisson_data,

family = quasipoisson(link = "log"))

##############################################
##################################

# EXERCISE 24: NONLINEAR CURVE FITTING

##############################################
##################################

cat("\n=== EXERCISE 24: NONLINEAR CURVE FITTING ===\n")

# Exponential growth data

x_exp <- 1:20

y_exp <- 10 * exp(0.1 * x_exp) + rnorm(20, 0, 5)

# Nonlinear least squares (NLS)

nls_model <- nls(y_exp ~ a * exp(b * x_exp),

start = list(a = 10, b = 0.1))

print("Nonlinear Model Summary:")

print(summary(nls_model))

# Plot fitted curve

plot(x_exp, y_exp, main = "Nonlinear Curve Fitting",

xlab = "X", ylab = "Y", pch = 19)


lines(x_exp, predict(nls_model), col = "red", lwd = 2)

# Logistic growth model

y_logistic <- 100 / (1 + exp(-0.5 * (x_exp - 10))) + rnorm(20, 0, 2)

logistic_model <- n

You might also like