title: “Homework 1” author: “Ducheley Richard” date: “2024-02-03” output: html_document
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
library(knitr)
library(TeachingDemos)
#loading the dataset
airpoll <- read.csv("~/Downloads/airpoll.txt", row.names=1, sep="")
View(airpoll)
stars(airpoll,nrow = 8)
faces(as.matrix(airpoll), fill = T, ncol = 6)
Examining the star plots we see that Miami is distinguished by a prominent arm indicating significant rainfall and a medium arm reflecting a respectable average education level. In contrast, cities such as San Francisco and Portland exhibit minimal rainfall. Meanwhile, Los Angeles, San Jose, and San Diego, which are neighboring cities, experience a moderate amount of rainfall. Los Angeles also has a substantial representation of non-white populations, a characteristic shared with Birmingham, AL; Atlanta, GA; Richmond, VA; and Greensboro, NC. York, PA, stands out for its high population density yet lower average education level. Furthermore, Baltimore and Chicago are notable for high mortality rates and elevated concentrations of sulfur dioxide. Encouragingly, it is observed that most cities have a low concentration of nitrogen oxides.
2.Produce a scatterplot matrix using “pairs” for this air pollution data set. Write a short paragraph explaining the main conclusions from the scatterplot matrix.
pairs(airpoll)
Upon examining the scatterplot matrix, one can argue that there exists a direct correlation between rainfall and the incidence of accidents. This relationship may be coincidental, or it may suggest that increased rainfall elevates the risk of accidents. Furthermore, we see a least squares pattern (parabolic in nature) between rainfall and the nonwhite population variable. There is also a discernible positive relationship between the nonwhite population variable and mortality rates. Moreover, it is plausible to suggest a weak, inverse correlation between education levels and mortality rates. A strong positive correlation is observed between NOx (Nitrogen Oxides) and SO2 (Sulfur Dioxide) concentrations; a slight increase in NOx appears to correlate with a significant increase in SO2 levels, with only a few outlier points disrupting this pattern. Lastly, a weak correlation between SO2 concentrations and mortality rates can also be inferred.
chiplot<-function(x,y,vlabs=c("X","Y"),matrix="NO") {
n<-length(x); ind<-numeric(length=n)
for(i in 1:n) {
for(j in (1:n)[-i]) if(x[i]>x[j]&y[i]>y[j]) ind[i]<-ind[i]+1
}
ind<-ind/(n-1); ind1<-numeric(length=n)
for(i in 1:n) {
for(j in (1:n)[-i]) if(x[i]>x[j]) ind1[i]<-ind1[i]+1
}
ind1<-ind1/(n-1); ind2<-numeric(length=n)
for(i in 1:n) {
for(j in (1:n)[-i]) if(y[i]>y[j]) ind2[i]<-ind2[i]+1
}
ind2<-ind2/(n-1)
s<-sign((ind1-0.5)*(ind2-0.5))
chi<-(ind-ind1*ind2)/sqrt(ind1*(1-ind1)*ind2*(1-ind2))
lambda<-4*s*pmax((ind1-0.5)^2,(ind2-0.5)^2)
thresh<-4*(1/(n-1)-0.5)^2
if(matrix=="NO") {
par(mfrow=c(1,2))
plot(x,y,xlab=vlabs[1],ylab=vlabs[2])
plot(lambda[abs(lambda)<thresh],chi[abs(lambda)<thresh],ylim=c(-1,1),xlab="lambda",
ylab="Chi"); abline(h=1.78/sqrt(n)); abline(h=-1.78/sqrt(n))}
if(matrix=="YES") {
plot(lambda[abs(lambda)<thresh],chi[abs(lambda)<thresh],ylim=c(-1,1))
abline(h=1.78/sqrt(n)); abline(h=-1.78/sqrt(n))}
}
attach(airpoll)
chiplot(Rainfall, Education, vlabs=c("Rainfall", "Education"))
It cannot be conclusively determined whether these two variables are independent, given that only a few more points lie outside of the horizontal band than within it.
chiplot(Popden, Nonwhite, vlabs =c("Popden", "Nonwhite"))
With some certainty we can conclude that these two variables are independent, as there is only a single point outside of the horizontal band.
chiplot(SO2, Mortality, vlabs =c("SO2", "Mortality"))
An almost clear departure from independence is observed here, with only several points situated within the horizontal band.
bivbox<-function(a, d = 7, mtitle = "Bivariate Boxplot",
method = "robust",xlab="X",ylab="Y")
{
#a is data matrix
#d is constant(usually 7)
p <- length(a[1, ])
if(method == "robust") {
param <- biweight(a[, 1:2]); m1 <- param[1]; m2 <- param[2]
s1 <- param[3]; s2 <- param[4]; r <- param[5]
}
else {
m1 <- mean(a[, 1]); m2 <- mean(a[, 2]);
s1 <- sqrt(var(a[, 1])); s2 <- sqrt(var(a[, 2])); r <- cor(a[, 1:2])[1, 2]
}
x <- (a[, 1] - m1)/s1; y <- (a[, 2] - m2)/s2
e <- sqrt((x * x + y * y - 2 * r * x * y)/(1 - r * r))
e2 <- e * e; em <- median(e); emax <- max(e[e2 < d * em * em])
r1 <- em * sqrt((1 + r)/2); r2 <- em * sqrt((1 - r)/2); theta <- ((2 * pi)/360) * seq(0, 360, 3)
xp <- m1 + (r1 * cos(theta) + r2 * sin(theta)) * s1; yp <- m2 + (r1 * cos(theta) - r2 * sin(theta)) * s2
r1 <- emax * sqrt((1 + r)/2); r2 <- emax * sqrt((1 - r)/2); theta <- ((2 * pi)/360) * seq(0, 360, 3)
xpp <- m1 + (r1 * cos(theta) + r2 * sin(theta)) * s1; ypp <- m2 + (r1 * cos(theta) - r2 * sin(theta)) * s2
maxxl <- max(xpp); minxl <- min(xpp); maxyl <- max(ypp); minyl <- min(ypp)
b1 <- (r * s2)/s1; a1 <- m2 - b1 * m1; y1 <- a1 + b1 * minxl; y2 <- a1 + b1 * maxxl
b2 <- (r * s1)/s2; a2 <- m1 - b2 * m2; x1 <- a2 + b2 * minyl; x2 <- a2 + b2 * maxyl
maxx <- max(c(a[, 1], xp, xpp, x1, x2)); minx <- min(c(a[, 1], xp, xpp, x1, x2))
maxy <- max(c(a[, 2], yp, ypp, y1, y2)); miny <- min(c(a[, 2], yp, ypp, y1, y2))
plot(a[, 1], a[, 2], xlim = c(minx, maxx), ylim = c(miny, maxy), xlab =xlab, ylab =ylab,
lwd = 2, pch = 1)
lines(xp, yp, lwd = 2); lines(xpp, ypp, lty = 2, lwd = 2)
segments(minxl, y1, maxxl, y2, lty = 3, lwd = 2); segments(x1, minyl, x2, maxyl, lty = 4, lwd = 2)
}
bivbox(cbind(Education, Mortality), xlab = "Education", ylab = "Mortality", method ="O")
A correlation between low mortality rates and high education levels is observed across most cities. The notable exception is Lancaster, PA, which, despite its lower average education level, also exhibits a low mortality rate, thereby distinguishing itself as an outlier. It is the one point outside of our oval. York, PA, situated precisely on our defined circumference, cannot be dismissed as an outlier. Interestingly, these two cities from Pennsylvania share the characteristic of having lower education averages while maintaining mortality rates below the average, presenting a noteworthy deviation from the observed trend.
plot(Education, Mortality, pch=1, lwd=2, ylim=c(750,1150), xlim=c(7.5,13))
# The x limits and y limits should be adjusted so that all the bubbles fit within the plotting window
symbols(Education, Mortality, circles=Popden, inches=0.4, add=T, lwd=2)
Observing the central points, it is evident that an inverse relationship exists between mortality rate and average education level; as the mortality rate increases, the average education level decreases. However, population density appears to be independent of both variables, as evidenced by bubbles of varying sizes distributed randomly across the graph. Notably, York, PA, is represented by the largest bubble, indicating the highest population density. Conversely, Dallas, Texas, is depicted with the smallest population density, marked by a bubble so small that its outer circle appears shaded.
ggplot(airpoll, aes(x = Nonwhite, y = Mortality, color = SO2, size = Popden)) +
geom_point(alpha = 0.7) + # Adjust point transparency with alpha
scale_color_gradient(low = "blue", high = "red") + # Customize color gradient
labs(title = "Nonwhite vs Mortality",
x = "Nonwhite",
y = "Mortality",
color = "SO2",
size = "Population Density") +
theme_minimal() +
guides(size = guide_legend(order = 1), color = guide_legend(order = 2))
library(superheat)
superheat(airpoll, scale = TRUE, bottom.label.text.size = 3, left.label.text.size = 2)