This document demonstrates how to create a dataframe, generate a plot, and compute statistics with interpretation using R.
First, we create three vectors and then combine them into a dataframe.
# Creating vectors
year <- c(2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023)
temperature <- c(15.1, 16.0, 16.5, 17.0, 17.2, 18.0, 18.5, 19.0, 19.5)
ice_cream_sales <- c(120, 150, 160, 170, 175, 180, 190, 200, 210)
# Combining vectors into a dataframe
df2 <- data.frame(year, temperature, ice_cream_sales)
# Viewing the dataframe
print(df2)
## year temperature ice_cream_sales
## 1 2015 15.1 120
## 2 2016 16.0 150
## 3 2017 16.5 160
## 4 2018 17.0 170
## 5 2019 17.2 175
## 6 2020 18.0 180
## 7 2021 18.5 190
## 8 2022 19.0 200
## 9 2023 19.5 210
# Linear regression between temperature and ice cream sales
model <- lm(ice_cream_sales ~ temperature, data = df2)
# Summary of the model
model_summary <- summary(model)
print(model_summary)
##
## Call:
## lm(formula = ice_cream_sales ~ temperature, data = df2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -9.854 -2.699 -1.183 4.268 6.330
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -149.25 23.76 -6.281 0.000412 ***
## temperature 18.48 1.36 13.593 2.74e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.573 on 7 degrees of freedom
## Multiple R-squared: 0.9635, Adjusted R-squared: 0.9583
## F-statistic: 184.8 on 1 and 7 DF, p-value: 2.743e-06
# Extracting model coefficients and R-squared value
intercept <- model_summary$coefficients[1, 1]
slope <- model_summary$coefficients[2, 1]
r_squared <- model_summary$r.squared
# Installing and loading the ggplot2 package
if(!require(ggplot2)) install.packages("ggplot2")
## Loading required package: ggplot2
library(ggplot2)
# Scatter plot for temperature and ice cream sales
ggplot(df2, aes(x = temperature, y = ice_cream_sales)) +
geom_point() +
geom_smooth(method = "lm", col = "blue") +
labs(title = "Temperature vs Ice Cream Sales", x = "Temperature (°C)", y = "Ice Cream Sales (Units)")
## `geom_smooth()` using formula = 'y ~ x'
The regression equation indicates that for each additional degree Celsius in temperature, ice cream sales increase by approximately r round(slope, 2) units. The R-squared value of r round(r_squared, 2) suggests that r round(r_squared * 100, 2)% of the variability in ice cream sales can be explained by the temperature.
These results demonstrate a significant positive impact of temperature on ice cream sales, highlighting the importance of warm weather in driving ice cream sales.