R markdown is a plain-text file format for integrating text and R code, and creating transparent, reproducible and interactive reports. An R markdown file (.Rmd) contains metadata, markdown and R code “chunks”, and can be “knit” into numerous output types. Answer the test questions by adding R code to the fenced code areas below each item. Once completed, you will “knit” and submit the resulting .html file, as well the .Rmd file. The .html will include your R code and the output.
Before proceeding, look to the top of the .Rmd for the (YAML) metadata block, where the title and output are given. Please change title from ‘Programming with R Test #2’ to your name, with the format ‘lastName_firstName.’
If you encounter issues knitting the .html, please send an email via Canvas to your TA.
Each code chunk is delineated by six (6) backticks; three (3) at the start and three (3) at the end. After the opening ticks, arguments are passed to the code chunk and in curly brackets. Please do not add or remove backticks, or modify the arguments or values inside the curly brackets.
Depending on the problem, grading will be based on: 1) the correct result, 2) coding efficiency and 3) graphical presentation features (labeling, colors, size, legibility, etc). I will be looking for well-rendered displays. In the “knit” document, only those results specified in the problem statements should be displayed. For example, do not output - i.e. send to the Console - the contents of vectors or data frames unless requested by the problem. You should be able to display each solution in fewer than ten lines of code.
Submit both the .Rmd and .html files for grading.
(1)(a) (6 points) The Poisson distribution may be used to approximate the binomial distribution if n > 20 and np < 7. Estimate the following binomial probabilities using dpois() or ppois() with probability p = 0.05, and n = 100. Then, estimate the same probabilities using dbinom() or pbinom(). Show the numerical results of your calculations.
n = 100
p = 0.05
lamb = n*p
dpois(0, lamb)
## [1] 0.006737947
dbinom(0, 100, .05)
## [1] 0.005920529
lower.tail logical; if TRUE (default), probabilities are P[X ??? x], otherwise, P[X > x].
lim = 6
sum(dpois(0:lim, lamb))
## [1] 0.7621835
sum(dbinom(0:lim, 100, .05))
## [1] 0.766014
The binomial may also be approximated via the normal distribution. Estimate the following binomial probabilities using dnorm() or pnorm(), this time with probability p = 0.2 and n = 100. Then, calculate the same probabilities using dbinom() and pbinom(). Use continuity correction. Show the numerical results of your calculations.
p = .2
n = 100
mean_val <- n*p
std_val <- sqrt(n*p*(1-p))
pnorm(25.5, mean_val, std_val) - pnorm(24.5, mean_val, std_val)
## [1] 0.04572879
dbinom(25, n, p)
## [1] 0.04387783
lower.tail logical; if TRUE (default), probabilities are P[X ??? x], otherwise, P[X > x].
pnorm(24.5, mean_val, std_val)
## [1] 0.8697055
pbinom(24, n, p)
## [1] 0.8686468
(1)(b) (3 points) Generate side-by-side barplots using par(mfrow = c(1,2)) or grid.arrange(). The left barplot will show Poisson probabilties for outcomes ranging from 0 to 10. The right barplot will show binomial probabilities for outcomes ranging from 0 to 10. Use p = 0.1 and n = 100. Title each plot, present in color and assign names to the bar; i.e. x-axis value labels.
p <- .1
n <- 100
bp_left_data <- dpois(0:10, n*p)
bp_right_data <- dbinom(0:10, n, p)
par(mfrow = c(1,2))
barplot(bp_left_data, main = "Poisson probabilities", xlab = "Outcome", ylab = "Probability", col = "steelblue")
barplot(bp_right_data, main = "Binomial probabilities", xlab = "Outcome", ylab = "Probability", col = "gray")
(1)(c) (6 points) For this problem, refer to Sections 5.2 of Business Statistics. A discrete random variable has outcomes: 0, 1, 2, 3, 4, 5, 6. The corresponding probabilities in sequence with the outcomes are: 0.215, 0.230, 0.240, 0.182, 0.130, 0.003, 0.001. In other words, the probabilty of obtaining “0” is 0.215.
outcomes <- seq(0,6)
probs <- c(.215, .230, .240, .182, .130, .003, .001)
exp_val <- round(sum(outcomes*probs), 1)
variance <- round((sum((outcomes-mean_val)^2*probs)), 1)
mean_val
## [1] 20
variance
## [1] 333.5
csum <- data.frame(Outcomes = outcomes, Cum_Probs = cumsum(probs))
ggplot(data = csum, aes(x = Outcomes, y = Cum_Probs)) +
geom_point(size = 2, col = "lightgreen") +
ggtitle("Cumulative Probabilities") +
ylab("Cumulative Probablities") +
geom_point(x = 3, y = median(csum$Cum_Probs), shape = 1, size = 6, col = "steelblue") +
geom_text(x = 4, y = .867, label = "Median = (3,.867)", col = "black")
(2)(a) (6 points) Load the “faithful” dataset and present summary statistics and a histogram of waiting times. Additionally, compute the empirical conditional probability of an eruption less than 3.5 minutes, if the waiting time exceeds 70 minutes.
data(faithful, package = "datasets")
summary(faithful)
## eruptions waiting
## Min. :1.600 Min. :43.0
## 1st Qu.:2.163 1st Qu.:58.0
## Median :4.000 Median :76.0
## Mean :3.488 Mean :70.9
## 3rd Qu.:4.454 3rd Qu.:82.0
## Max. :5.100 Max. :96.0
hist(faithful$waiting, xlab = "Waiting time (mins)", main = "Histogram of Waiting Times", col = "pink")
wait_data <- faithful[which(faithful$waiting > 70),]
erupt_data <- faithful[which(faithful$eruptions < 3.5),]
cond_probability <- nrow(erupt_data)/nrow(wait_data)
cat("Conditional Probability", cond_probability, "\n")
## Conditional Probability 0.630303
selected_data <-faithful[which(faithful$eruptions > 5 & faithful$waiting > 90),]
selected_data
## eruptions waiting
## 149 5.1 96
ggplot(data=faithful,mapping = aes(x=waiting,y=eruptions)) +
geom_point()+geom_hline(yintercept = 5,linetype="dashed", col="cyan") +
geom_vline(xintercept = 90,linetype="dashed", col="purple") +
geom_point(data=selected_data,aes(x=waiting,y=eruptions),color="steelblue2") +
labs(x="Waiting Time (min)",y="Eruptions") +
ggtitle("Eruptions vs Waiting Time")
Answer: (Below the 60 minute wait time, the eruptions are between 1 through 3. The least number of eruption frequencies occur between the 60 to 70 minute wait time. The wait times between 70 to 90 minutes, the eruptions are higher in frequency between 4 and 5.)
(2)(b) (6 points) Past research indicates that the waiting times between consecutive eruptions are not independent. This problem will check to see if there is evidence of this. Form consecutive pairs of waiting times. In other words, pair the first and second waiting times, pair the third and fourth waiting times, and so forth. There are 136 resulting consecutive pairs of waiting times. Form a data frame with the first column containing the first waiting time in a pair and the second column with the second waiting time in a pair. Plot the pairs with the second member of a pair on the vertical axis and the first member on the horizontal axis.
One way to do this is to pass the vector of waiting times - faithful$waiting - to matrix(), specifying 2 columns for our matrix, with values organized by row; i.e. byrow = TRUE.
df <- data.frame(matrix(faithful$waiting, ncol = 2, byrow = TRUE))
colnames(df) <- c("FWT","SWT")
ggplot(data = df, mapping = aes(x = FWT, y = SWT)) +
geom_point() +
ggtitle("Paired Waiting Times") +
labs(x = "First Waiting Time (min)", y = "Second Waiting Time (min)")
(2)(c) (3 points) Test the hypothesis of independence with a two-sided test at the 99% confidence level using the Kendall correlation coefficient. The cor.test() function can be used to structure this test and specify the appropriate - Kendall’s tau - method.
cor.test(df$FWT,df$SWT, alternative = "two.sided", method = "kendall", conf.level = .99)
##
## Kendall's rank correlation tau
##
## data: df$FWT and df$SWT
## z = -4.9482, p-value = 7.489e-07
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
## tau
## -0.2935579
# load "ChickWeight" dataset
data(ChickWeight, package = "datasets")
# There are multiple ways to approach the subsetting task. The method you choose is up
# to you.
result <- data.frame(subset(ChickWeight, Time == 21 & (Diet==1 | Diet==3)))
# The values in your subsetted data frame should match those below:
# > head(df)
# weight Time Chick Diet
# 12 205 21 1 1
# 24 215 21 2 1
# 36 202 21 3 1
# 48 157 21 4 1
# 60 223 21 5 1
# 72 157 21 6 1
(3)(a) (3 points) Display two side-by-side vertical boxplots using par(mfrow = c(1,2)). One boxplot would display Diet “1” and the other Diet “3”.
d1_data <- subset(result, Diet == 1)
d3_data <- subset(result, Diet == 3)
par(mfrow=c(1,2))
boxplot(d1_data$weight, main="Diet 1 Data", ylab="Chick Weight(gram)",col="lightblue")
boxplot(d3_data$weight, main="Diet 3 Data", ylab="Chick Weight(gram)",col="blue")
(3)(b) (3 points) Use the “weight” data for the two diets to test the null hypothesis of equal population mean weights for the two diets. Test at the 95% confidence level with a two-sided t-test. This can be done using t.test() in R. Do not assume equal variances. Display the results of t.test().
t.test(d1_data$weight ,d3_data$weight, conf.level = 0.95, alternative ="two.sided", var.equal = FALSE)
##
## Welch Two Sample t-test
##
## data: d1_data$weight and d3_data$weight
## t = -3.4293, df = 16.408, p-value = 0.003337
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -149.64644 -35.45356
## sample estimates:
## mean of x mean of y
## 177.75 270.30
# There are multiple ways to approach the subsetting task. The method you choose is up
# to you.
time_20 <- subset(ChickWeight$weight, ChickWeight$Diet==3 & ChickWeight$Time==20)
time_21 <- subset(ChickWeight$weight, ChickWeight$Diet==3 & ChickWeight$Time==21)
# The first six (6) elements of your Time == 20 vector should match those below:
# [1] 235 291 156 327 361 225
(3)(c) (3 points) Present a scatterplot of the Time == 21 weights as a function of the Time == 20 weights. Include a diagonal line with zero intercept and slope equal to one. Title and label the variables in this scatterplot.
diet_3 <- data.frame(x=time_20, y=time_21)
colnames(diet_3) <- c("weight20", "weight21")
ggplot(diet_3, aes(x=weight20, y = weight21)) +
geom_point(size = 1, color="blue") +
geom_abline(intercept=0, slope=1, color="violet", linetype=2) +
ggtitle("Weight Gain between Day 20 and 21") +
xlab("Weights at Day 20 (grams)") +
ylab("Weights at Day 21 (grams)")
(3)(d) (6 points) Calculate and present a one-sided, 95% confidence interval for the average weight gain from day 20 to day 21. Write the code for the paired t-test and for determination of the confidence interval endpoints. **Do not use *t.test()**, although you may check your answers using this function. Present the resulting test statistic value, critical value, p-value and confidence interval.
gain <- diet_3$weight21 - diet_3$weight20
n <- length(gain)
df <- n-1
sd <- sd(gain)
mean <- mean(gain)
t_stat <- (mean-0)/(sd/sqrt(n))
cat("Test Statistic Value: ", t_stat, "\n")
## Test Statistic Value: 3.225267
t_crit <- qt(.95, df)
cat("Critical Value: ", t_crit, "\n")
## Critical Value: 1.833113
p_val <- pt(t_stat, df, lower=FALSE)
cat("P-value: ", p_val, "\n")
## P-value: 0.00520061
err <- t_crit*(sd/sqrt(n))
ci_u <- mean - err
cat("One-Sided Confidence Interval: (", ci_u, ", oo)\n")
## One-Sided Confidence Interval: ( 4.920696 , oo)
data(Nile, package = "datasets")
m <- mean(Nile)
std <- sd(Nile)
x <- seq(from = 400, to = 1400, by = 1)
hist(Nile, freq = FALSE, col = "darkblue", xlab = "Flow",
main = "Histogram of Nile River Flows, 1871 to 1970")
curve(dnorm(x, mean = m, sd = std), col = "cyan", lwd = 2, add = TRUE)
(4)(a) (3 points) Using Nile River flow data and the “moments” package, calculate skewness and kurtosis. Present a QQ plot and boxplot of the flow data side-by-side using qqnorm(), qqline() and boxplot(); par(mfrow = c(1, 2)) may be used to locate the plots side-by-side. Add features to these displays as you choose.
library(moments)
skewness(Nile)
## [1] 0.3223697
kurtosis(Nile)
## [1] 2.695093
par(mfrow = c(1, 2))
qqnorm(Nile, col="darkblue", main="QQ Plot of Nile River Flows", cex=.75)
qqline(Nile)
boxplot(Nile, horizontal=FALSE, notch=TRUE, col="lightgreen", main="Boxplot of Nile River Flows", ylab="Flow")
(4)(b) (6 points) Using set.seed(456) and the Nile data, generate 1000 random samples of size n = 16, with replacement. For each sample drawn, calculate and store the sample mean. This can be done with a for-loop and use of the sample() function. Label the resulting 1000 mean values as “sample1”. Repeat these steps using set.seed(789) - a different “seed” - and samples of size n = 64. Label these 1000 mean values as “sample2”. Compute and present the means, sample standard deviations and sample variances for “sample1” and “sample2” in a table with the first row for “sample1”, the second row for “sample2” and the columns labled for each statistic.
set.seed(456)
sample1 <- rep(1:1000,0)
sample2 <- rep(1:1000,0)
for(i in 1:1000) {sample1[i] <- mean(sample(Nile, 16, replace=TRUE), na.rm=TRUE)}
set.seed(789)
for(i in 1:1000) {sample2[i] <- mean(sample(Nile, 64, replace=TRUE), na.rm=TRUE)}
means <- c(mean(sample1), mean(sample2))
sds <- c(sd(sample1), sd(sample2))
vars <- c(var(sample1), var(sample2))
samp_sum <- cbind(means, sds, vars)
colnames(samp_sum) <- c("Mean", "Std Dev", "Variance")
rownames(samp_sum) <- c("sample1", "sample2")
samp_sum
## Mean Std Dev Variance
## sample1 919.7673 41.95021 1759.8201
## sample2 919.0662 21.35711 456.1263
(4)(c) (6 points) Present side-by-side histograms of “sample1” and “sample2” with the normal density curve superimposed. To prepare comparable histograms, it will be necessary to use “freq = FALSE” and to maintain the same x-axis with “xlim = c(750, 1050)”, and the same y-axis with “ylim = c(0, 0.025).” To superimpose separate density functions, you will need to use the mean and standard deviation for each “sample” - each histogram - separately.
# Create histograms of "sample1" and "sample2" with normal density curves superimposed
par(mfrow = c(1, 2))
hist(sample1, freq=FALSE, xlim=c(750, 1050), ylim=c(0,0.025), col="darkblue")
curve(dnorm(x, mean = mean(sample1), sd = sd(sample1)), col = "cyan", lwd = 2, add = TRUE)
hist(sample2, freq=FALSE, xlim=c(750, 1050), ylim=c(0,0.025), col="darkblue")
curve(dnorm(x, mean = mean(sample2), sd = sd(sample2)), col = "cyan", lwd = 2, add = TRUE)
(5)(a)(5 points) warpbreaks is part of the “datasets” package and may be loaded via data(warpbreaks). Load “warpbreaks” and present the structure using str(). Calculate the median number of breaks for the entire dataset, disregarding “tension” and “wool”. Define this median value as “median_breaks”. Present a histogram of the number of breaks with the location of the median indicated.
Create a new variable “number” as follows: for each value of “breaks”, classify the number of breaks as either strictly below “median_breaks”, or the alternative. Convert the “above”|“below” classifications to a factor, and combine with the dataset warpbreaks. Present a summary of the augmented dataset using summary(). Present a contingency table of the frequency of breaks using the two variables “wool” and “number”. There should be four cells in this table.
data(warpbreaks, package = "datasets")
str(warpbreaks)
## 'data.frame': 54 obs. of 3 variables:
## $ breaks : num 26 30 54 25 70 52 51 26 67 18 ...
## $ wool : Factor w/ 2 levels "A","B": 1 1 1 1 1 1 1 1 1 1 ...
## $ tension: Factor w/ 3 levels "L","M","H": 1 1 1 1 1 1 1 1 1 2 ...
median_breaks <- median(warpbreaks$breaks)
hist(warpbreaks$breaks, main="Histogram of Loom Warp Breaks", xlab="Warp Breaks per Loom")
abline(v = median_breaks, col = "red")
text(x=37, y=15,"Median = 26", col="red")
number <- factor(ifelse(warpbreaks$breaks < median_breaks, "below", "above"))
warpbreaks <- cbind(warpbreaks, number)
summary(warpbreaks)
## breaks wool tension number
## Min. :10.00 A:27 L:18 above:29
## 1st Qu.:18.25 B:27 M:18 below:25
## Median :26.00 H:18
## Mean :28.15
## 3rd Qu.:34.00
## Max. :70.00
cont <- table(warpbreaks$tension, warpbreaks$number)
cont
##
## above below
## L 14 4
## M 10 8
## H 5 13
(5)(b)(3 points) Using the table constructed in (5)(a), test at the 5% level the null hypothesis of independence using the uncorrected chisq.test() (Black, Business Statistics, Section 16.2). Show the results of this test and state your conclusions.
chisq.test(cont, correct=FALSE)
##
## Pearson's Chi-squared test
##
## data: cont
## X-squared = 9.0869, df = 2, p-value = 0.01064
#As the Chi-squared value is significantly larger than the p-value, we reject the null hypothesis and conclude that the variables are not independent.
(5)(c) (3 points) ‘Manually’ calculate the chi-squared statistic and p-value of the table from (5)(a). The addmargins() function can be used to add row and column sums to the table; useful for calculating the expected values for each cell. You should be able to match the chi-squared and p-values from (5)(b). The underlying code for the chisq.test() function can be viewed by entering chisq.test - without parentheses - in the Console. You are given code below to create the table, add row and column sums and calculate the expected values for the for the first of two (2) rows. You will need to add code to calculate the expected values for the second row and the chi-squared. The pchisq() function can be used to return the p-value.
tbl <- table(warpbreaks$wool, warpbreaks$number)
mar_tbl <- addmargins(tbl)
e11 <- mar_tbl[3, 1] * mar_tbl[1, 3] / mar_tbl[3, 3]
e12 <- mar_tbl[3, 2] * mar_tbl[1, 3] / mar_tbl[3, 3]
chi_sq_stat <- ((mar_tbl[1,1]-e11)^2/e11) + ((mar_tbl[1,2]-e12)^2/e12)
cat("Chi-squared statistic: ",chi_sq_stat,"\n")
## Chi-squared statistic: 0.3351724
p_val <- pchisq(chi_sq_stat, 2, lower.tail=FALSE)
cat("P-value: ", p_val)
## P-value: 0.8457037
(5)(d) (4 points) Build a user-defined function, using your code for (5)(c).We want to pass our (5)(a) table to our function and have it return the chi-squared statistic and p-value. You’re provided with the ‘shell’ of a function and will need to add code to calculate the expected values, the chi-squared statistic, the p-value and return (i.e. output) the chi-squared and p-value.
chisq_function <- function(x) {
# Code for calculating the expected values
mar_tbl <- addmargins(x)
e11 <- mar_tbl[3, 1] * mar_tbl[1, 3] / mar_tbl[3, 3]
e12 <- mar_tbl[3, 2] * mar_tbl[1, 3] / mar_tbl[3, 3]
# Code for calculating the chi-squared
chiSq <- ((x[1,1]-e11)^2/e11) + ((x[1,2]-e12)^2/e12)
# Code for calculating the degrees of freedom and p-value
df <- nrow(x)-1
p_val <- pchisq(chiSq, df, lower.tail=FALSE)
# Code to ouput the chi-squared, degrees of freedom and p-value
return(list("chi-squared" = chiSq,
"degrees of freedom" = df,
"p-value" = p_val))
}
chisq_function(tbl)
## $`chi-squared`
## [1] 0.3351724
##
## $`degrees of freedom`
## [1] 1
##
## $`p-value`
## [1] 0.5626291
You do not need to do anything with the below. It is provided only for demonstration purposes. In (5)(d), we know the size of the table - 2 x 2 - and write a function to match. Often, though, we’ll want to write functions that are flexible in some way.
# Below is a function that should return the same values as chisq.test() and your
# function from (5)(d). Here, though, the function loops over the rows and columns
# to calculate the expected values. Ideally, this function would work for any sized
# table.
chisqfun <- function(t) {
x <- addmargins(t)
e <- matrix(0, nrow = nrow(t), ncol = ncol(t), byrow = T)
r <- matrix(0, nrow = nrow(t), ncol = ncol(t), byrow = T)
for (i in 1:dim(t)[1]) {
for (j in 1:dim(t)[2]) {
e[i,j] = x[nrow(x),j] * x[i,ncol(x)]/x[nrow(x), ncol(x)]
r[i,j] = ((x[i,j] - e[i,j])^2)/e[i,j]
}
}
chi <- sum(r)
xdf <- (nrow(t) - 1) * (ncol(t) - 1)
pv <- pchisq(chi, df = xdf, lower.tail = FALSE)
return(list("chi-squared" = chi, "degrees_of_freedom" = xdf, "p-value" = pv))
}