Project 2 (Fall 2026)

Author

Surafel Haile

Project 2 : Weather Patterns and Temperature Across the United States

Introduction:

The dataset used for this project is the weather dataset. It contains weather observations form different weather stations and includes information about station location, precipitation, temperature, wind direction and wind speed. For my analysis, I will use both categorical and quantitative variables. The categorical variables include state and city, which describe the locations of the weather stations. The quantitative variables include average temperature, precipitation, and wind speed. My research question for this project will be how do temperature, precipitation, and wind conditions relate to average weekly temperature across different U.S. cities?

Data source : Weather.csv

Loading the libraries:

#Loading the appropriate libraries:
library(tidyverse)
Warning: package 'tidyverse' was built under R version 4.5.3
Warning: package 'readr' was built under R version 4.5.3
Warning: package 'dplyr' was built under R version 4.5.3
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.2     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.1     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(readr)
library(ggplot2)
library(highcharter)
Warning: package 'highcharter' was built under R version 4.5.3
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo 
Highcharts (www.highcharts.com) is a Highsoft software product which is
not free for commercial and Governmental use
library(RColorBrewer)
library(plotly)
Warning: package 'plotly' was built under R version 4.5.3

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout
setwd("C:/Users/suraf/OneDrive/New folder") #set the working directory.
weather <- read.csv("weather.csv") #Read the weather dataset from the CSV file.
head(weather) #Display the first few rows.
  Data.Precipitation Date.Full Date.Month Date.Week.of Date.Year Station.City
1               0.00  1/3/2016          1            3      2016   Birmingham
2               0.00  1/3/2016          1            3      2016   Huntsville
3               0.16  1/3/2016          1            3      2016       Mobile
4               0.00  1/3/2016          1            3      2016   Montgomery
5               0.01  1/3/2016          1            3      2016    Anchorage
6               0.09  1/3/2016          1            3      2016      Annette
  Station.Code Station.Location Station.State Data.Temperature.Avg.Temp
1          BHM   Birmingham, AL       Alabama                        39
2          HSV   Huntsville, AL       Alabama                        39
3          MOB       Mobile, AL       Alabama                        46
4          MGM   Montgomery, AL       Alabama                        45
5          ANC    Anchorage, AK        Alaska                        34
6          ANN      Annette, AK        Alaska                        38
  Data.Temperature.Max.Temp Data.Temperature.Min.Temp Data.Wind.Direction
1                        46                        32                  33
2                        47                        31                  32
3                        51                        41                  35
4                        52                        38                  32
5                        38                        29                  19
6                        44                        31                   9
  Data.Wind.Speed
1            4.33
2            3.86
3            9.73
4            6.86
5            7.80
6            8.70

Checking the variables(Exploring the data):

glimpse(weather)#Display the dimensions of the dataset.
Rows: 16,743
Columns: 14
$ Data.Precipitation        <dbl> 0.00, 0.00, 0.16, 0.00, 0.01, 0.09, 0.05, 0.…
$ Date.Full                 <chr> "1/3/2016", "1/3/2016", "1/3/2016", "1/3/201…
$ Date.Month                <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
$ Date.Week.of              <int> 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,…
$ Date.Year                 <int> 2016, 2016, 2016, 2016, 2016, 2016, 2016, 20…
$ Station.City              <chr> "Birmingham", "Huntsville", "Mobile", "Montg…
$ Station.Code              <chr> "BHM", "HSV", "MOB", "MGM", "ANC", "ANN", "B…
$ Station.Location          <chr> "Birmingham, AL", "Huntsville, AL", "Mobile,…
$ Station.State             <chr> "Alabama", "Alabama", "Alabama", "Alabama", …
$ Data.Temperature.Avg.Temp <int> 39, 39, 46, 45, 34, 38, 30, 22, 34, 38, 31, …
$ Data.Temperature.Max.Temp <int> 46, 47, 51, 52, 38, 44, 36, 32, 36, 43, 39, …
$ Data.Temperature.Min.Temp <int> 32, 31, 41, 38, 29, 31, 24, 9, 31, 33, 23, 4…
$ Data.Wind.Direction       <int> 33, 32, 35, 32, 19, 9, 9, 2, 20, 9, 14, 2, 1…
$ Data.Wind.Speed           <dbl> 4.33, 3.86, 9.73, 6.86, 7.80, 8.70, 16.46, 3…
colSums(is.na(weather)) #Check for missing values.
       Data.Precipitation                 Date.Full                Date.Month 
                        0                         0                         0 
             Date.Week.of                 Date.Year              Station.City 
                        0                         0                         0 
             Station.Code          Station.Location             Station.State 
                        0                         0                         0 
Data.Temperature.Avg.Temp Data.Temperature.Max.Temp Data.Temperature.Min.Temp 
                        0                         0                         0 
      Data.Wind.Direction           Data.Wind.Speed 
                        0                         0 

Here, I checked the dataset for missing values using is.na() and colSums(). The results showed zero missing values for all 14 variables, indicating that the dataset does not contain any missing observations. Further more glimpse(weather) to quickly examine the structure and contents of the weather dataset.

Cleaning/ organizing the data:

#Select the variables needed for the analysis and change the names:
weather_clean <- weather %>%
  select(
    State = Station.State,
    City = Station.City,
    Precipitation = Data.Precipitation,
    AvgTemp = Data.Temperature.Avg.Temp,
    MaxTemp = Data.Temperature.Max.Temp,
    MinTemp = Data.Temperature.Min.Temp,
    WindSpeed = Data.Wind.Speed
  )

head(weather_clean)
    State       City Precipitation AvgTemp MaxTemp MinTemp WindSpeed
1 Alabama Birmingham          0.00      39      46      32      4.33
2 Alabama Huntsville          0.00      39      47      31      3.86
3 Alabama     Mobile          0.16      46      51      41      9.73
4 Alabama Montgomery          0.00      45      52      38      6.86
5  Alaska  Anchorage          0.01      34      38      29      7.80
6  Alaska    Annette          0.09      38      44      31      8.70

This code creates a cleaned version of the weather dataset by selecting only the variables needed for the analysis and giving those variables simpler names. It then displays the first few rows of the cleaned dataset. Select () is used to choose specific columns from the dataset.

Regression Analysis:

#Build a multiple linear regression model:
weather_model <- lm(AvgTemp ~ MaxTemp + MinTemp + Precipitation + WindSpeed, data = weather_clean)
#Display the regression results:
summary(weather_model)

Call:
lm(formula = AvgTemp ~ MaxTemp + MinTemp + Precipitation + WindSpeed, 
    data = weather_clean)

Residuals:
    Min      1Q  Median      3Q     Max 
-14.739  -0.250  -0.219   0.255  47.223 

Coefficients:
                Estimate Std. Error t value Pr(>|t|)    
(Intercept)    0.2743552  0.0269393  10.184   <2e-16 ***
MaxTemp        0.5005973  0.0007646 654.738   <2e-16 ***
MinTemp        0.4987595  0.0008155 611.593   <2e-16 ***
Precipitation  0.0061426  0.0058908   1.043    0.297    
WindSpeed     -0.0022413  0.0016480  -1.360    0.174    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.7208 on 16738 degrees of freedom
Multiple R-squared:  0.9985,    Adjusted R-squared:  0.9985 
F-statistic: 2.842e+06 on 4 and 16738 DF,  p-value: < 2.2e-16

The multiple linear regression model showed that maximum temperature and minimum temperature were significant predictors of average temperature, with both having p-values less than 0.001. However, precipitation (p = 0.297) and wind speed (p = 0.174) were not statistically significant predictors. The model had a very high adjusted R-squared value of 0.9985, meaning that approximately 99.85 % of the variation in average temperature was explained by the predictors in the model. Based on these results, precipitation and wind speed can be considered for removal from the model.

Reduced model :

# Create a simpler model using the significant predictors:
weather_model <- lm(AvgTemp ~ MaxTemp + MinTemp , data = weather_clean)
#Dispaly the regression results:
summary(weather_model)

Call:
lm(formula = AvgTemp ~ MaxTemp + MinTemp, data = weather_clean)

Residuals:
    Min      1Q  Median      3Q     Max 
-14.748  -0.250  -0.226   0.255  47.224 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 0.2579320  0.0213235    12.1   <2e-16 ***
MaxTemp     0.5006408  0.0007244   691.1   <2e-16 ***
MinTemp     0.4988235  0.0007724   645.8   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.7209 on 16740 degrees of freedom
Multiple R-squared:  0.9985,    Adjusted R-squared:  0.9985 
F-statistic: 5.684e+06 on 2 and 16740 DF,  p-value: < 2.2e-16

In this reduced model, after removing precipitation and wind speed from the linear regression model, we see that the adjusted R-squared value didn’t change. This means that those variables were not adding meaningful explanatory power to the model. The conclusion isn’t that precipitation and wind speed aren’t necessarily useless, but rather they can serve as extra layers of information for our visualizations.

Visualizations :

#Create U.S. Region Cohorts
weather_clean <- weather_clean %>%
  mutate(
    Region = case_when(
      State %in% c("Connecticut", "Maine", "Massachusetts",
                   "New Hampshire", "Rhode Island", "Vermont",
                   "New Jersey", "New York", "Pennsylvania") ~ "Northeast",
      
      State %in% c("Illinois", "Indiana", "Michigan", "Ohio", "Wisconsin",
                   "Iowa", "Kansas", "Minnesota", "Missouri",
                   "Nebraska", "North Dakota", "South Dakota") ~ "Midwest",
      
      State %in% c("Delaware", "Florida", "Georgia", "Maryland",
                   "North Carolina", "South Carolina", "Virginia",
                   "West Virginia", "Alabama", "Kentucky", "Mississippi",
                   "Tennessee", "Arkansas", "Louisiana", "Oklahoma", "Texas") ~ "South",
      
      State %in% c("Arizona", "Colorado", "Idaho", "Montana", "Nevada",
                   "New Mexico", "Utah", "Wyoming", "Alaska",
                   "California", "Hawaii", "Oregon", "Washington") ~ "West",
    )
  )
head(weather_clean$Region)
[1] "South" "South" "South" "South" "West"  "West" 

Here created four regional groups—Northeast, Midwest, South, and West—by assigning each state to a region using case_when (). The code uses mutate() to add a new Region variable to the weather_clean () dataset. Each state is matched to its corresponding region. Finally, head(weather_clean$Region) displays the first few region values to confirm that the new variable was created correctly.

# Summarize the Two Regions
weather_region_summary <- weather_clean %>%
  filter(Region %in% c("Northeast", "South")) %>%
  group_by(Region) %>%
  summarise(
    AvgMinTemp = mean(MinTemp),
    AvgMaxTemp = mean(MaxTemp),
    AvgWindSpeed = mean(WindSpeed)
  )
head(weather_region_summary)
# A tibble: 2 × 4
  Region    AvgMinTemp AvgMaxTemp AvgWindSpeed
  <chr>          <dbl>      <dbl>        <dbl>
1 Northeast       42.8       60.4         7.44
2 South           54.6       75.3         5.84

This code summarizes the weather data for the Northeast and South regions. First, filter() keeps only observations from those two regions. Then, group_by(Region) organizes the data by region, and summarise() calculates the average minimum temperature, average maximum temperature, and average wind speed for each region. The resulting table shows that the South has higher average minimum and maximum temperatures than the Northeast, while the average wind speeds are relatively similar.

# Interactive Regional Temperature Comparison:
region_plot <- ggplot(
  weather_region_summary,
  aes(x = Region)
) +
  geom_col(
    aes(y = AvgMinTemp, fill = "Average Minimum Temperature")
  ) +
  geom_col(
    aes(y = AvgMaxTemp, fill = "Average Maximum Temperature"),
    position = "dodge"
  ) +
  labs(
    title = "Average Minimum and Maximum Temperatures: Northeast vs. South",
    x = "U.S. Region",
    y = "Temperature (°F)",
    fill = "Temperature Measure",
    caption = "Source: National Weather Service"
  ) +
  theme_minimal()

ggplotly(region_plot)

The first graph shows a clear temperature difference between the two regions. The Northeast has an average minimum temperature of about 42.8°F and an average maximum temperature of about 60.4°F, while the South has higher averages of about 54.6°F and 75.3°F, respectively. Overall, the South is noticeably warmer than the Northeast in both minimum and maximum temperatures.

# Calculate the difference between maximum and minimum temperature
weather_clean <- weather_clean %>%
  mutate(
    TempRange = MaxTemp - MinTemp
  )
# Calculate the average temperature range for the West and Midwest
temp_range_west_midwest <- weather_clean %>%
  filter(Region %in% c("West", "Midwest")) %>%
  group_by(Region) %>%
  summarise(
    AvgTempRange = mean(TempRange)
  )

# Display the results
head(temp_range_west_midwest)
# A tibble: 2 × 2
  Region  AvgTempRange
  <chr>          <dbl>
1 Midwest         20.8
2 West            20.7

This code creates a new TempRange variable by subtracting the minimum temperature from the maximum temperature for each observation. It then filters the dataset to include only the West and Midwest regions and groups the data by region. Finally, summarise() calculates the average temperature range for each region. The results show an average temperature range of about 20.80°F for the Midwest and 20.68°F for the West.

city_temp_range <- weather_clean %>%
  group_by(City, Region) %>%
  summarise(
    AvgTempRange = mean(TempRange),
    .groups = "drop"
  )

# Select the 10 cities with the largest average temperature ranges
top_10_cities <- city_temp_range %>%
  arrange(desc(AvgTempRange)) %>%
  slice_head(n = 10)

# Display the results
top_10_cities
# A tibble: 10 × 3
   City           Region AvgTempRange
   <chr>          <chr>         <dbl>
 1 Bishop         West           38.1
 2 Alamosa        West           36.5
 3 Douglas Bisbee West           35.4
 4 Winslow        West           34  
 5 Craig          West           33.7
 6 Pueblo         West           33.6
 7 Ely            West           33.5
 8 Winnemucca     West           33.4
 9 China Lake     West           32.7
10 Dalhart        South          32.2

This code calculates the average temperature range for each city by grouping the data by city and region and taking the mean of TempRange. It then sorts the cities from the largest to smallest average temperature range and selects the top 10 cities.

ggplot(
  top_10_cities,
  aes(
    x = reorder(City, AvgTempRange),
    y = AvgTempRange,
  fill = Region)
) +
  geom_col() +
  coord_flip() +
  labs(
    title = "Top 10 Cities by Average Temperature Range",
    x = "City",
    y = "Average Temperature Range (°F)",
    fill = "U.S. Region",
    caption = "Source: National Weather Service"
  ) +
  theme_minimal()

The graph shows that Bishop has the largest average temperature range at about 38°F, followed by Alamosa at about 36.5°F. The other cities have average temperature ranges between approximately 32°F and 35°F. Most of the cities shown are located in the West, while Dalhart is the only city from the South, suggesting that the largest temperature ranges in this dataset are concentrated primarily in Western cities.