# Load the dataset
zillow_data_raw <- read.csv("zillowmorgantown.csv",
                            skip = 3) %>% 
  clean_names() %>% # Clean column names
  select(-mls_id, -broker_name, -broker_agent)  # Remove NA columns

# Convert 'sold_date' to Date object and extract year, month, day
# Convert all lot_land_area values to sqft
zillow_data <- zillow_data_raw %>%
  mutate(
    sold_date = mdy(sold_date_mm_dd_yyyy),
    sold_year = year(sold_date),
    sold_month = month(sold_date),
    sold_day = day(sold_date),
    lot_area_sqft = if_else(lot_land_area_unit == "acres", lot_land_area * 43560, lot_land_area),
    living_area_sqft = living_area
  ) %>%
  select(-sold_date_mm_dd_yyyy, -lot_land_area_unit, -lot_land_area, -living_area_unit, -living_area) # Remove original date and lot area columns

# Check for outliers in price
ggplot(zillow_data, aes(x = property_price_usd)) + geom_boxplot() +
  scale_x_continuous(labels = scales::dollar_format())

# Removing outliers
# Filter out property prices outside the range of $100,000 to $800,000, and living_area_sqft outliers
zillow_data <- zillow_data %>%
  filter(property_price_usd >= 100000, property_price_usd <= 800000, living_area_sqft < 5000)

# Remove NA Values
zillow_data <- na.omit(zillow_data)

# Create the multiple linear regression model
model <- lm(property_price_usd ~ sold_year + sold_month + living_area_sqft + lot_area_sqft + bedrooms + bathrooms, data = zillow_data)
summary(model)
## 
## Call:
## lm(formula = property_price_usd ~ sold_year + sold_month + living_area_sqft + 
##     lot_area_sqft + bedrooms + bathrooms, data = zillow_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -254738  -48102   -5512   56002  402570 
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      -4.335e+06  1.497e+07  -0.290 0.772390    
## sold_year         2.151e+03  7.399e+03   0.291 0.771518    
## sold_month        6.778e+02  1.812e+03   0.374 0.708657    
## living_area_sqft  1.192e+02  1.078e+01  11.049  < 2e-16 ***
## lot_area_sqft     4.906e-01  1.527e-01   3.213 0.001480 ** 
## bedrooms         -1.258e+04  5.920e+03  -2.125 0.034504 *  
## bathrooms         2.810e+04  8.059e+03   3.487 0.000573 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 81420 on 260 degrees of freedom
## Multiple R-squared:  0.6964, Adjusted R-squared:  0.6894 
## F-statistic:  99.4 on 6 and 260 DF,  p-value: < 2.2e-16
# Check correlations between variables
correlations <- cor(select(zillow_data, property_price_usd, sold_year, sold_month, living_area_sqft, lot_area_sqft, bedrooms, bathrooms), use = "complete.obs")
print(correlations)
##                    property_price_usd  sold_year  sold_month living_area_sqft
## property_price_usd         1.00000000 -0.2297642  0.05251787       0.81443910
## sold_year                 -0.22976421  1.0000000 -0.29414640      -0.27672300
## sold_month                 0.05251787 -0.2941464  1.00000000       0.04829601
## living_area_sqft           0.81443910 -0.2767230  0.04829601       1.00000000
## lot_area_sqft             -0.01309041 -0.1352221 -0.06423013      -0.15664151
## bedrooms                   0.51601306 -0.2063640 -0.01067428       0.71042279
## bathrooms                  0.72184434 -0.1799980  0.06166545       0.80777590
##                    lot_area_sqft    bedrooms   bathrooms
## property_price_usd   -0.01309041  0.51601306  0.72184434
## sold_year            -0.13522206 -0.20636402 -0.17999802
## sold_month           -0.06423013 -0.01067428  0.06166545
## living_area_sqft     -0.15664151  0.71042279  0.80777590
## lot_area_sqft         1.00000000 -0.23376202 -0.17138199
## bedrooms             -0.23376202  1.00000000  0.59681253
## bathrooms            -0.17138199  0.59681253  1.00000000
# Visualizing the relationship between living area and property price
ggplot(zillow_data, aes(x = living_area_sqft, y = property_price_usd)) +
  geom_point(alpha = 0.5) +
  geom_smooth(method = lm, se = FALSE, color = "blue") +
  labs(title = "Property Price vs. Living Area", x = "Living Area (sqft)", y = "Property Price (USD)")
## `geom_smooth()` using formula = 'y ~ x'

# Create the multiple linear regression model
model_formula <- property_price_usd ~ sold_year + sold_month + living_area_sqft + lot_area_sqft + bedrooms + bathrooms

# Fit the model
model <- lm(model_formula, data = zillow_data)
# Output model summary
model_summary <- summary(model)
cat(paste("The model indicates a strong relationship between the living area square footage and the property sale price, with an adjusted R-squared of 0.6894. This means that about 68.94% of the variability in the property prices can be explained by the living area.  \n\nModel Summary:\n"),
    sep = "\n")
## The model indicates a strong relationship between the living area square footage and the property sale price, with an adjusted R-squared of 0.6894. This means that about 68.94% of the variability in the property prices can be explained by the living area.  
## 
## Model Summary:
print(model_summary)
## 
## Call:
## lm(formula = model_formula, data = zillow_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -254738  -48102   -5512   56002  402570 
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      -4.335e+06  1.497e+07  -0.290 0.772390    
## sold_year         2.151e+03  7.399e+03   0.291 0.771518    
## sold_month        6.778e+02  1.812e+03   0.374 0.708657    
## living_area_sqft  1.192e+02  1.078e+01  11.049  < 2e-16 ***
## lot_area_sqft     4.906e-01  1.527e-01   3.213 0.001480 ** 
## bedrooms         -1.258e+04  5.920e+03  -2.125 0.034504 *  
## bathrooms         2.810e+04  8.059e+03   3.487 0.000573 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 81420 on 260 degrees of freedom
## Multiple R-squared:  0.6964, Adjusted R-squared:  0.6894 
## F-statistic:  99.4 on 6 and 260 DF,  p-value: < 2.2e-16
# Calculate and print RMSE for the model
calculate_rmse <- function(model, data) {
  predictions <- predict(model, data)
  residuals <- data$property_price_usd - predictions
  sqrt(mean(residuals^2))
}
train_rmse <- calculate_rmse(model, zillow_data)
print(paste("RMSE on the training data:", train_rmse))
## [1] "RMSE on the training data: 80347.0526981839"
# Adjusted R-squared
# Check adjusted R-squared is > 0.52
print(paste("Adjusted R-squared on the training data:", model_summary$adj.r.squared))
## [1] "Adjusted R-squared on the training data: 0.689390103456962"
# Visualization of the Model
# Visualize the model's predictions vs. actual property prices
ggplot(zillow_data, aes(x = predict(model), y = property_price_usd)) +
  geom_point() +
  geom_smooth(method = "lm") +
  scale_x_continuous(labels = scales::dollar_format(), breaks = c(200000, 400000, 600000)) +
  scale_y_continuous(labels = scales::dollar_format(), breaks = c(200000, 400000, 600000)) +
  labs(title = "Predicted vs. Actual Property Prices", 
       x = "Predicted Price (USD)", 
       y = "Actual Price (USD)")
## `geom_smooth()` using formula = 'y ~ x'