–Welcome to Lecture#8,Chapter V.
Let us start by finding our working directory.
getwd()
[1] "/Users/tomandrews/Desktop/Data Mining & Machine Learning/In Class Activities"
# make sure the packages for this chapter are installed, install if necessary
pkg <- c("ggplot2", "scales",
"sp", "maps", "grid", "car" )
new.pkg <- pkg[!(pkg %in% installed.packages())]
if (length(new.pkg)) {
install.packages(new.pkg)
}
install.packages("ggplot2")
Error in install.packages : Updating loaded packages
Let us now make sure that the file zero access is uploaded into your new project. Then let us define the variable za.
#Choose the CSV file interactively
file_path <- file.choose()
#Read the CSV file into R
za <- read.csv(file_path)
# View(za) - the view function creates a new tab when it is run so we comment that out and just use za
za
THE DATA SET # Latitude and longitude are a system of lines used to describe the location of any place on Earth. Lines of latitude run in an east-west direction across Earth. Lines of longitude run in a north-south direction.
The header = TRUE argument indicates that the first row of the CSV file contains column headers, and sep = “,” specifies that the comma (,) is used as the separator between values.
# Load ggplot2 to create graphics
library(ggplot2)
# create a ggplot instance with the zeroaccess dataset
gg <- ggplot(data=za, aes(x=long, y=lat))
# add the points, set transparency to 1/40th
gg <- gg + geom_point(size=1, color="#000099", alpha=1/40)
# add axes labels
gg <- gg + xlab("Longitude") + ylab("Latitude")
# simplify the theme for aesthetics
gg <- gg + theme_bw()
# this may take a while, over 800,000 points plotted
print(gg)
# Or you can run the same thing with the below code which was how i was first taught to use R
#ggplot(za, aes(x = long, y = lat)) +
#geom_point(size = 1, color = "#000099", alpha = 1/40) +
#theme_bw()
install.packages("mapproj")
trying URL 'https://cran.rstudio.com/bin/macosx/big-sur-arm64/contrib/4.3/mapproj_1.2.11.tgz'
Content type 'application/x-gzip' length 84829 bytes (82 KB)
==================================================
downloaded 82 KB
The downloaded binary packages are in
/var/folders/hp/sg5rh0q973706k_nx5hscbmh0000gn/T//RtmpcZUshg/downloaded_packages
library(mapproj)
Loading required package: maps
library(ggplot2)
# install.packages("ggplot2")
# requires package : ggplot2
# requires object: za (5-1)
# the "maps" and "mapproj" packages are used by ggplot
# load map data of the world
world <- map_data("world")
#Remove Antarctica
world <- subset(world, world$region!="Antarctica")
# load world data into ggplot object
gg <- ggplot(data=world, aes(x=long, y=lat))
# trace along the lat/long co-ords by group (countries)
gg <- gg + geom_path(aes(group=group), colour="gray70")
# now project using the mercator projection
# try different projections with ?mapproject
gg <- gg + coord_map("mercator", xlim=c(-200, 200))
# load up the ZeroAccess points, overiding the default data set
gg <- gg + geom_point(data=za, aes(long, lat),
colour="#000099", alpha=1/40, size=1)
# remove text, axes ticks, grid lines and do gray border on white
#gg <- gg + theme(text=element_blank(),
# axis.ticks=element_blank(),
# panel.grid=element_blank(),
# panel.background=element_rect(color="gray50",
# fill="white"))
print(gg)
# Assuming 'gg' is your ggplot object
# If not, replace 'gg' with your ggplot object
# Create a basic ggplot object
gg <- ggplot(data = world, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "lightgray", color = "white") +
theme_minimal()
# Project using the Mercator projection
gg_mercator <- gg + coord_map("mercator", xlim = c(-200, 200))
# Print the plot
print(gg_mercator)
#Interpret the output above. The resulting data set (world) contains information about the boundaries and coordinates of countries.
#Let us proceed to define the file county.dataset found on blackboard.
# read up census data per county
#Choose the CSV file interactively
file_path <- file.choose()
#Read the CSV file into R
county.data <- read.csv(file_path)
county.data
# requires objects: input (5-16)
# generate output around a mean of 2 x input
output <- rnorm(200, mean=input*2)
# put into data frame to plot it
our.data <- data.frame(input, output)
gg <- ggplot(our.data, aes(input, output))
gg <- gg + geom_point()
gg <- gg + geom_smooth(method = "lm", se=F, color="red")
gg <- gg + theme_bw()
print(gg)
# Customize the graph
gg <- gg +
labs(title = "Scatter Plot with Linear Regression",
x = "Input",
y = "Output") +
theme_minimal()
# Print the customized graph
print(gg)
#Make comments about both the syntax and the output of the task executed above. Is it possible to customize this graph to make it more explanatory? If so explain and run the code - this code is above The first line of code generates a new set of random numbers (output) from a normal distribution with a mean twice the values in the existing input vector. A scatter plot is then created with a regression line to measure how output changes as input increases The code added to make it more expkanatory was labels and a title
Let us now run output vs input.
model <- lm(output ~ input)
summary(model)
Call:
lm(formula = output ~ input)
Residuals:
Min 1Q Median 3Q Max
-2.38985 -0.55765 0.04897 0.57751 2.33511
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.34865 0.68284 1.975 0.0496 *
input 1.87974 0.06775 27.744 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.888 on 198 degrees of freedom
Multiple R-squared: 0.7954, Adjusted R-squared: 0.7944
F-statistic: 769.7 on 1 and 198 DF, p-value: < 2.2e-16
yes it is significant if it’s lower than 0.05 (pvalue) which it is
yes it is significant if it’s lower than 0.01 (pvalue) which it is
confint(model)
2.5 % 97.5 %
(Intercept) 0.002090649 2.695217
input 1.746133210 2.013355
^^^ If it doesn’t go through zero, it is signficant. The input here is significant whilst the intercept is not.
Using the county.data dataset, let us run a model of Infections vs ufo2010 (Alien Sightings)
summary(lm(county.data$Infections ~ county.data$ufo2010, data= county.data))
Call:
lm(formula = county.data$Infections ~ county.data$ufo2010, data = county.data)
Residuals:
Min 1Q Median 3Q Max
-407.50 -70.35 -5.78 60.05 2736.39
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 124.77740 2.38569 52.302 < 2e-16 ***
county.data$ufo2010 0.56899 0.07998 7.114 1.4e-12 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 127.5 on 3070 degrees of freedom
Multiple R-squared: 0.01622, Adjusted R-squared: 0.0159
F-statistic: 50.61 on 1 and 3070 DF, p-value: 1.398e-12
# the hypothesis here is that in the different regions of the USA, there is not enough
# evidence that more reports of UFO sightings affect the no of infections
Yes it is significant because the p value is lower than 0.05
It is also significant at a 1% significance level due to the P value being lower than 0.01
summary(lm(Infections ~ pop + income + ipaddr + ufo2010,
data=county.data))
Call:
lm(formula = Infections ~ pop + income + ipaddr + ufo2010, data = county.data)
Residuals:
Min 1Q Median 3Q Max
-342.94 -70.34 -5.40 58.85 2745.36
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.000e+02 9.426e+00 10.610 < 2e-16 ***
pop -1.615e-05 1.543e-05 -1.047 0.29510
income 5.670e-04 2.066e-04 2.745 0.00609 **
ipaddr -9.865e-08 5.148e-07 -0.192 0.84803
ufo2010 6.804e-01 1.691e-01 4.024 5.85e-05 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 127.3 on 3067 degrees of freedom
Multiple R-squared: 0.01879, Adjusted R-squared: 0.01751
F-statistic: 14.69 on 4 and 3067 DF, p-value: 6.915e-12
The income and number of UFO sightings are significant because the p value is less than 0.05 and 0.01 The population and IP Address are not significant variables according to the numbers As a whole, the variables are significant and have an impact on the number of infections
#Interpret the output. How would you proceed from now on in this handout given the results obtained above. The bottom overall P value is less than 0.05 and therefore the variables are significant within the model in terms of how they affect each other
install.packages("carData")
trying URL 'https://cran.rstudio.com/bin/macosx/big-sur-arm64/contrib/4.3/carData_3.0-5.tgz'
Content type 'application/x-gzip' length 1825505 bytes (1.7 MB)
==================================================
downloaded 1.7 MB
The downloaded binary packages are in
/var/folders/hp/sg5rh0q973706k_nx5hscbmh0000gn/T//Rtmpei4F0F/downloaded_packages
library(car) # for the vif() function
Let us just explore the variance inflation factor (VIF) of the model to see if there is a chance of high correlation between my predictors. I remind you that a strong correlation between two of my predictors will likely end up in heteroskedasticity, and therefore our model would not be accurate.
model <- lm(Infections ~ pop + income + ipaddr + ufo2010,
data=county.data)
sqrt(vif(model))
pop income ipaddr ufo2010
2.165458 1.038467 1.046051 2.115512
#Let us see if population affects the number of infections in this data set. Write the null and alternative hypothesis you would use to test this relationship.
Null: The population size does not have a statistically significant impact on the number of infections
Alt: The population size has a statistically significant effect on the number of infections
summary(lm(Infections ~ pop, data=county.data))
Call:
lm(formula = Infections ~ pop, data = county.data)
Residuals:
Min 1Q Median 3Q Max
-365.26 -70.35 -5.70 59.59 2724.00
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.250e+02 2.416e+00 51.755 < 2e-16 ***
pop 4.228e-05 7.147e-06 5.916 3.67e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 127.8 on 3070 degrees of freedom
Multiple R-squared: 0.01127, Adjusted R-squared: 0.01095
F-statistic: 35 on 1 and 3070 DF, p-value: 3.668e-09
Interpret the results obtained above # We can assume that the null hypothesis is correct because the p value is less than 0.05 and so population size does have a significant effect on the number of infections
Now let us define the regression of Infections vs pop as pop.lm and predict the number of infections based on the variable population.
pop.lm <- lm(Infections ~ pop, data=county.data)
predict(pop.lm, data.frame(pop=6000000), interval="confidence")
fit lwr upr
1 378.7109 295.9209 461.5009
predict(pop.lm, data.frame(pop=1000000), interval="confidence")
fit lwr upr
1 167.3069 153.9224 180.6915
predict(pop.lm, data.frame(pop=2000000), interval="confidence")
fit lwr upr
1 209.5877 182.5947 236.5807
If the population is 6 million, the (FIT) most likely value of infections is 379 and the lower and upper quartiles show as 296 up to 462. If the lower and upper are close to the fit, then the most likely value can be seen as more accurate than not. It can be said that as we take a higher population measure, the predictability is less accurate.
pop.lm <- lm(Infections ~ pop, data=county.data)
predict(pop.lm, data.frame(pop=2000000), interval="confidence")
fit lwr upr
1 209.5877 182.5947 236.5807
predict(pop.lm, data.frame(pop=10000), interval="confidence")
fit lwr upr
1 125.449 120.7524 130.1456
If the population is 2 million, the (FIT) most likely value of infections is 210 and the lower and upper quartiles show as 183 up to 236. If the lower and upper are close to the fit, then the most likely value can be seen as more accurate and in this case it looks more accurate than the population being measured as 6 million because there is less data being measured
The number of infections compared to whether there were 2 million is surprising.
This now shows that when the income is at $10,000, the the most likely value of infections is 100
The number of infections when the salary is at $40,000 seems to be higher than when at $10,000.
Is there a correlation between higher incomes having more infections? NO, I don’t think so and therefore it could be said that income is not a significant factor.