1/23
Looks like no tags are added yet.
HW 3
Question 1: Filling NAs
Use replace_na to replace all NAs by zeros, and store the result as diatoms1. Store rows 94 and 95 of the resulting dataframe as diatoms_mod1_examplerows and display these rows.
diatoms1 <- diatoms_raw |> mutate(across(everything(), \(x) replace_na(x, 0)))
diatoms_mod1_examplerows <- diatoms1 |> slice(94:95)
HW 3
Question 2: Counts to proportions
Convert the counts to proportions by dividing the diatom counts by the total number of phytoplankton recorded in the Num.counted column. You can do this succinctly using the across function. Note that the proportions of diatoms will not sum to 1 since Num.counted includes all phytoplankton counts, many of which are not diatoms but other groups.
In addition, multiply the Age variable by -1.
diatoms2 <- diatoms1 |> mutate(across(all_of(c("A_curv", "A_octon", "ActinSpp",
"A_nodul", "CoscinSpp", "CyclotSpp", "Rop_tess", "StephanSpp")),
\(x) x / Num.counted), Age = Age * -1)
HW 3
Question 3: Time span
What is the geological time span covered by the data? Compute the age of the oldest and newest samples. Express the ages in years.
oldest_age <- min(diatoms2Age)<em>−1</em>1000</p><p>newestage<−max(diatoms2Age) -1 1000
print(c(oldest_age, newest_age))
HW 3
Question 4: Time resolution
(i) How are the observations spaced in time?
Follow these steps:
Use diatoms2 and the arrange function to sort the Age column in ascending order, from smallest (most negative) to largest. Then create a new column called Gap which is the gap in ages between consecutive samples. You can do this using the diff function. For example diff(c(2, 7, 8, 10)) returns 5, 1, 2. Note that the length of the vector returned by diff is 1 less than the length of the input, since there is no gap that we can compute for the first observation. To create the Gap column, set the first value of Gap to NA and the rest to the result of diff called on the Age column. Save the updated data to diatoms3.
Make a simple count histogram with bins of width 0.02 (20 years). Store this as gap_histogram and display the figure.
Label the x axis 'Time step between consecutive samples'
Put the y axis on a square root scale so that bins with just one observation are more visible. You can do this by setting the y aesthetic to after_stat(sqrt(count)).
# store differences
diatoms3 <- diatoms2 |> arrange(Age) |> mutate(Gap = c(NA, diff(Age)))
gap_histogram <- ggplot(diatoms3, aes(x = Gap)) +
geom_histogram(binwidth = 0.02, aes(y = after_stat(sqrt(count)))) +
labs(x = "Time Step Between Consecutive Samples", y = "Count (Square Root Scale)")
gap_histogram
HW 3
Question 5: Summary statistics
Use summarize(across(A_curv:StephanSpp, ...)) to summarize the mean and standard deviation of the relative diatom abundances in diatoms3.
diatom_summary <- diatoms3 |> summarize(across(A_curv:StephanSpp,
list(mean = mean, sd=sd)),.names = "{.col}_{.fn}")
# print the dataframe
diatom_summary
HW 3
Question 6: Most and least abundant taxa
It will be easier to determine which taxa are most/least abundant by reorganizing the dataframe.
diatom_summary2 <- diatom_summary |> select(-.names) |>
pivot_longer(
cols = everything(),
names_pattern = "(.+)_(mean|sd)$",
names_to = c("taxon", "statistic"),
values_to = "value"
) |> pivot_wider(names_from=statistic, values_from=value)
HW 3
Question 7: Distribution of diatom abundances over time
(i) Use the diatoms3 dataframe to make a line plot of Age vs relative abundance faceted by taxon. Set scales="free" in the call to facet_wrap to give each facet its own y-scale. You may need to pivot_longer on diatoms3 to make plotting easier.
long <- diatoms3 |> pivot_longer(cols = A_curv:StephanSpp, names_to = "Taxon",
values_to = "Abundance")
diatom_abundances_plot <- ggplot(long, aes(x = Age, y = Abundance)) +
geom_line() + facet_wrap(~ Taxon, scales = "free") +
labs(x="Age", y="Relative Abundance",
title = "Age vs Relative Abundance (faceted by taxon)")
HW 3
Question 8: Conditional distributions of relative abundance
(i) Plot separate kernel density estimates to show the distribution of relative abundances both before and after 11KyrBP.
long <- long |> mutate(time = ifelse(Age < -11, "Before 11KyrBP",
"After 11KyrBP"))
A_nodul <- long |> filter(Taxon == "A_nodul")
ggplot(A_nodul, aes(x = Abundance, color = time, fill = time)) +
geom_density(alpha = 0.2) +
labs(
title = "Kernal Density Estimate of Relative Abundance of Azpeitia Nodulifer",
x = "Relative Abundance", y = "Density",
color = "time", fill = "time")
HW 3
Question 9: Abundance and sea surface temperature (Kernal Smoothing)
## ksmooth returns its fit sorted by x, so sort the diatom data by Age first
diatoms3 <- diatoms3 |> arrange(Age)
## Kernel smooth of sea surface temperature, evaluated at the diatom ages
sst_smooth <- ksmooth(seatempsAge,seatempsSST,
kernel = "normal", bandwidth = 0.5,
x.points = diatoms3Age)
## Add the predicted sea surface temperature to the diatom data
diatoms3sst_pred <- sst_smooth$y
Make a scatterplot of each taxon's relative abundance against the predicted sea surface temperature, faceting by taxon. With facet_wrap, use scales="free" to give every plot its own y-limits. Hint: you may need to pivot_longer on diatoms3 first.
sst_v_diatoms_plot <- diatoms3|>
pivot_longer(cols = A_curv:StephanSpp, names_to = "Taxon",
values_to = "Abundance")|>
ggplot(aes(x = sst_pred, y = Abundance)) + geom_point() +
facet_wrap(~Taxon, scales = "free") + labs(x = "Predicted Sea Surface Temperature",
y = "Relative Abundance",
title = "Relative Abundance Against the Predicted Sea Surface Temperature")
sst_v_diatoms_plot
HW 3
Question 10: Pairwise correlations in relative abundances
(i) Compute the pairwise correlations between relative abundances and make a plot visualizing the correlation matrix.
corrmatrix <- cor(diatoms3 |> select(A_curv:StephanSpp))
corrplot(corrmatrix, method = "ellipse", diag=FALSE)
HW 3
Question 11: Computing and selecting principal components
diatom_pca <- diatoms3 |> select(A_curv:StephanSpp) |>
prcomp(x = _, scale = TRUE)
pc_vars <- data.frame(pc = 1:8, var = diatom_pcasdev2,</p><p>varexplained=(diatompcasdev^2)/sum(diatom_pcasdev2),</p><p>cumvarexplained=cumsum(diatompcasdev^2)/sum(diatom_pca$sdev^2))
var_exp_plot <- ggplot(pc_vars, aes(x=pc, y=var_explained)) + geom_col() +
labs(x = "PC", y = "Variance Explained", title = "Variance Explained By Each PC")
cum_var_exp_plot <- ggplot(pc_vars, aes(x=pc, y=cum_var_explained)) +
geom_line() + coord_cartesian(ylim = c(0, 1)) +
labs(x = "PC", y = "Cumumulative Variance Explained",
title = "Cumulative Variance Explained")
var_exp_plot + cum_var_exp_plot
HW 3
Question 12: Interpreting component loadings
(i) Make barplots showing the component loadings for the first two principal components
# Get loadings
loadings <- data.frame(diatom_pcarotation[,1:2],Taxon=rownames(diatompcarotation))
pc1_loadings <- ggplot(loadings, aes(x = Taxon, y = PC1)) + geom_col() +
labs(x = "Taxon", y = "Loadings", title = "Component Loadings for PC1")
pc2_loadings <- ggplot(loadings, aes(x = Taxon, y = PC2)) + geom_col() +
labs(x = "Taxon", y = "Loadings", title = "Component Loadings for PC2")
pc1_loadings / pc2_loadings
HW 3
Question 13: Visualizing community composition shift
(i) Construct a scatterplot of PC1 and PC2 scores by epoch.
projected_data <- data.frame(PC1 = diatom_pcax[,1],PC2=diatompcax[,2],
Age = diatoms3$Age) |> mutate(Epoch = ifelse(Age < -11, "Pleistocene", "Holocene"))
pc_scores_plot <- ggplot(projected_data, aes(x = PC1, y = PC2, color = Epoch)) + geom_point()+
labs(x = "PC1", y = "PC2", title = "Scatterplot of PC1 and PC2 Scores By Epoch")
pc_scores_plot
HW 3
Question 14: Multi-panel visualization
Sometimes it's helpful to see marginal distributions together with a scatterplot.
ggMarginal(pc_scores_plot, groupFill = TRUE)
HW 4
Question 2: Alleged discrimination
Construct a data frame showing the median expenditure for each ethnicity, along with the sample size for each ethnic group, sorted from the largest group to the smallest.
median_expend_by_eth <- dds |> group_by(Ethnicity) |>
summarise(Median = median(Expenditures), samplesize = n()) |>
arrange(desc(samplesize))
HW 4
Question 3: Plot median expenditures
Construct a point-and-line plot of median expenditure (y) against ethnicity (x)
median <- dds |> group_by(Ethnicity) |>
summarise(Median = median(Expenditures), samplesize = n()) |>
arrange(desc(Median))
fig_1 <- ggplot(median, aes(x=Ethnicity, y=Median)) + geom_point() +
geom_line(aes(group = 1)) + scale_y_log10() +
labs(y = "Median expenditure", x=NULL, title = "Median Expenditure vs. Ethnicity")
HW4
Question 4: Age and expenditure
How does expenditure differ by age? Construct a scatterplot of expenditure (y) against age (x).
fig_2 <- ggplot(dds, aes(x=Age, y=Expenditures)) + geom_point() +
scale_y_log10() + labs(title = "Expenditures vs. Age")
HW 4
Question 5: Age structure of the sample
Here you'll explore the age composition of each ethnic group in the sample.
Count the number of consumers in each combination of ethnicity and age cohort. Use dds_cat so that the order of age cohorts is preserved. Store the result as samp_sizes.
Construct a point-and-line plot of the sample size (y) against age cohort (x), with one line per ethnic group (mapped to color). Make sure the age cohorts appear in order on the x-axis. Store the plot as fig_3 and display it.
samp_sizes <- dds_cat |> group_by(Ethnicity, Age.Cohort) |>
summarise(samplesize = n())
fig_3 <- ggplot(samp_sizes, aes(x=Age.Cohort, y=samplesize,
color = Ethnicity, group = Ethnicity)) + geom_point() +
geom_line() + labs(x = "Age Cohort", y = "Sample Size",
title = "Sample Size vs. Age Cohort")
print(fig_3)
HW4
Question 6: Correcting for age
Construct a point-and-line chart based on dds_cat with:
fig_4 <- dds_cat |> group_by(Ethnicity, Age.Cohort) |>
summarise(Median = median(Expenditures)) |>
ggplot(aes(x = Ethnicity, y = Median, color = Age.Cohort)) +
geom_point() + geom_line(aes(group = Age.Cohort)) +
scale_y_log10() + labs(y = "Median Expenditure", x=NULL,
title = "Median Expenditure vs. Ethnicity (By Age)")
HW 4
Question 7: The unadjusted difference
We'll start by comparing minorities and non-minorities without any adjustment. Define "non-minority" as "White not Hispanic" and "minority" as all other ethnicities.
Add a logical variable named Minority to dds_cat (TRUE for minority consumers).
Write a function, compute_mean_diff, that takes a data frame and returns the mean expenditure of minority consumers minus the mean expenditure of non-minority consumers (in dollars). Apply it to dds_cat.
Bootstrap this difference: resample whole rows (consumers) of dds_cat with replacement 1000 times, as in lecture, and apply compute_mean_diff to each bootstrap sample. Plot a histogram of the bootstrap distribution, and compute a 95% bootstrap percentile confidence interval.
## (i) add Minority to dds_cat
dds_cat <- dds_cat |> mutate(Minority = (Ethnicity != "White not Hispanic"))
## (ii) difference in mean expenditure
compute_mean_diff <- function(data) {
minmean <- data |> filter(Minority == TRUE) |> summarize(mean(Expenditures)) |> pull()
nonminmean <- data |> filter(Minority == FALSE) |> summarize(mean(Expenditures)) |> pull()
minmean - nonminmean
}
compute_mean_diff(dds_cat)
## (iii) bootstrap
set.seed(100)
n_bootstrap <- 1000
boot_mean_diff <- numeric(n_bootstrap)
for (rep_id in 1:n_bootstrap) {
bootsample <- dds_cat[sample(1:nrow(dds_cat), size = nrow(dds_cat), replace = TRUE), ]
boot_mean_diff[rep_id] <- compute_mean_diff(bootsample)
}
## 95% confidence interval and histogram
print(quantile(boot_mean_diff, c(0.05/2, 1-0.05/2)))
hist(boot_mean_diff, main = "Bootstrap of Mean Expenditure Differences",
xlab = "Difference in Mean Expenditures (Minority - Non Minority)")
HW 4
Question 8: Using IPW to adjust for age
Write a function, compute_adjusted_diff, that takes a data frame and returns the age-adjusted difference. First add the propensity score as a column e_x (hint: group_by(`Age Cohort`) |> mutate(e_x = mean(Minority)) |> ungroup()), then compute the weights and the two weighted means. Apply it to dds_cat.
Bootstrap compute_adjusted_diff 1000 times, as in Question 7. Plot a histogram of the bootstrap distribution with a dashed vertical line at 0, and compute a 95% bootstrap percentile confidence interval.
compute_adjusted_diff <- function(data) {
data <- data |> group_by(Age.Cohort) |> mutate(e_x = mean(Minority)) |> ungroup()|>
mutate(wi = ifelse(Minority == TRUE, 1/e_x, 1/(1-e_x)))
mmean <- data |> filter(Minority == TRUE) |>
summarise(sum(Expenditures * wi)/ sum(wi)) |> pull()
nmmean <- data |> filter(Minority == FALSE) |>
summarise(sum(Expenditures * wi)/ sum(wi)) |> pull()
mmean - nmmean
}
compute_adjusted_diff(dds_cat)
## (ii) bootstrap
set.seed(101)
boot_adjusted_diff <- numeric(n_bootstrap)
for (rep_id in 1:n_bootstrap) {
bootsample <- dds_cat[sample(1:nrow(dds_cat), size = nrow(dds_cat), replace = TRUE), ]
boot_adjusted_diff[rep_id] <- compute_adjusted_diff(bootsample)
}
## 95% confidence interval and histogram
print(quantile(boot_adjusted_diff, c(0.05/2, 1-0.05/2)))
hist(boot_adjusted_diff, main = "Histogram of Bootstrap Adjusted for Age",
xlab = "Difference in Mean Expenditures (Adjusted for Age)")
abline(v=0, col = "darkgreen", lty = 2)
HW 4
Question 10: Model fitting
Fit the linear regression of log(Expenditures) on Age Cohort, Gender, and Ethnicity (in that order), using dds_lm. Store the result as expenditures_fit.
expenditures_fit <- lm(log(Expenditures) ~ Age.Cohort + Gender + Ethnicity, data = dds_lm)
coef_tbl <- tidy(expenditures_fit) |>
mutate(ratio = exp(estimate)) |>
select(term, estimate, std.error, ratio)
HW 4
Question 12: Bootstrap confidence intervals
The std.error column comes from a formula that assumes the spread of log expenditures around the model is the same for every consumer. As in lecture, we'll use the paired bootstrap instead, which doesn't need that assumption.
Resample whole rows of dds_lm with replacement 1000 times. For each bootstrap sample, refit the model from Question 10 and save three coefficients: EthnicityHispanic, GenderMale, and `Age Cohort`22 to 50. The code below pulls these out by name with coef(boot_fit)[terms]. We don't save the whole coefficient vector because the small groups from Question 2 are missing from some bootstrap samples, and lm() then returns fewer coefficients.
Complete the table boot_summary. For each of the three coefficients, it should show the estimate, the formula standard error (std.error from Question 10), the bootstrap standard error, and a 95% bootstrap percentile confidence interval. Exponentiate the interval for EthnicityHispanic and interpret it in one sentence, comparing consumers of the same age cohort and gender. Is there evidence of a gender difference?
The two standard errors are about the same for EthnicityHispanic and GenderMale, but not for `Age Cohort`22 to 50. Compute the standard deviation of log expenditures within each age cohort, and use it to explain why. (Hint: the 22 to 50 coefficient compares the 22-50 cohort with the 0-5 cohort. What does the formula assume about the spread?)
terms <- c("EthnicityHispanic", "GenderMale", "Age.Cohort22 to 50")
## (i) paired bootstrap
set.seed(200)
boot_coefs <- matrix(NA, nrow = n_bootstrap, ncol = length(terms),
dimnames = list(NULL, terms))
for (rep_id in 1:n_bootstrap) {
boot_dds <- dds_lm[sample(1:nrow(dds_lm), size = nrow(dds_lm), replace = TRUE),] # resample whole rows of dds_lm
boot_fit <- lm((log(Expenditures)) ~ Age.Cohort + Ethnicity + Gender, data = boot_dds) # refit the Question 10 model
boot_coefs[rep_id, ] <- coef(boot_fit)[terms]
}
## (ii) summary table: one row per coefficient
boot_summary <- tibble(
term = terms,
estimate = coef(expenditures_fit)[terms],
formula_se = summary(expenditures_fit)coefficients[terms, "Std. Error"],
boot_se = apply(boot_coefs, 2, sd),
lower = apply(boot_coefs, 2, quantile, probs = 0.025, na.rm = TRUE),
upper = apply(boot_coefs, 2, quantile, probs = 0.975, na.rm = TRUE)
)
boot_summary
## Hispanic interval on the ratio scale
exp(boot_summarylower[boot_summaryterm=="EthnicityHispanic"])</p><p>exp(bootsummaryupper[boot_summary$term == "EthnicityHispanic"])
## (iii) standard deviation of log expenditures in each age cohort
dds_lm |> group_by(Age.Cohort) |> summarise(logexpsd = sd(log(Expenditures)))