# Load necessary libraries
library(readxl) # For reading Excel files
library(dplyr) # For data manipulation
library(broom) # For tidying outputs (e.g., PCA results)
library(ggplot2) # For optional visualization
# Step 1: Read the Excel file
# Replace 'your_file_path.xlsx' with the actual path to your Excel file
# Assume your sheet name is "Sheet1" and columns are named: Apartment_ID, Factor1, Factor2, ..., Factor10, Final_Score
data <- read_excel("your_file_path.xlsx", sheet = "Sheet1")
# Step 2: Data Exploration and Preprocessing
# View the first few rows to confirm the structure
head(data)
# Select only the factor columns (assume they are named Factor1 to Factor10)
# If your column names differ, update the vector below
factor_columns <- paste0("Factor", 1:10) # e.g., c("Factor1", "Factor2", ..., "Factor10")
# Check for missing values and handle them (e.g., remove rows with NA)
data_clean <- data %>%
select(Apartment_ID, all_of(factor_columns), Final_Score) %>% # Select relevant columns
filter(complete.cases(.)) # Remove rows with missing values
# Standardize the factors (important for PCA to ensure all are on the same scale)
data_standardized <- data_clean %>%
mutate(across(all_of(factor_columns), scale)) # Scales each factor to mean=0, SD=1
# Step 3: Perform Principal Component Analysis (PCA)
# Run PCA on the standardized factors
pca_result <- prcomp(data_standardized[, factor_columns], scale. = FALSE) # scale.=FALSE because we already standardized
# Extract the loadings from the first principal component
# These loadings will be used as the weights
weights <- pca_result$rotation[, 1] # First PC loadings
weights_df <- data.frame(
Factor = factor_columns,
Weight = weights
)
# Print the weights
print(weights_df)
# Interpretation: Each weight represents the contribution of that factor to the first principal component.
# The sum of squared weights should be close to 1 (as they are loadings).
# Step 4: Compute a New Weighted Score Using the Derived Weights
# Apply the weights to the standardized factors to create a new score
new_weighted_score <- as.matrix(data_standardized[, factor_columns]) %*% weights # Matrix multiplication
data_standardized <- data_standardized %>%
mutate(New_Weighted_Score = new_weighted_score)
# Compare the new weighted score to the original Final_Score
# Add the original Final_Score for comparison (assuming it's not standardized)
data_with_scores <- data_standardized %>%
mutate(Original_Final_Score = data_clean$Final_Score) # Merge back the original score
# Calculate correlation between Original_Final_Score and New_Weighted_Score
correlation <- cor(data_with_scores$Original_Final_Score, data_with_scores$New_Weighted_Score)
print(paste("Correlation between Original Final_Score and New Weighted Score:", round(correlation, 3)))
# Step 5: Visualize and Evaluate
# Plot the first two principal components for insight (optional, but helpful)
pca_summary <- summary(pca_result)
print(pca_summary) # Shows variance explained by each PC
# Scree plot to confirm the first PC explains most variance
scree_plot <- ggplot(data.frame(PC = 1:length(pca_result$sdev), Variance = pca_result$sdev^2)) +
geom_line(aes(x = PC, y = Variance)) +
geom_point(aes(x = PC, y = Variance)) +
labs(title = "Scree Plot", x = "Principal Component", y = "Variance Explained") +
theme_minimal()
print(scree_plot)
# Rank apartments based on the new weighted score
data_with_scores <- data_with_scores %>%
mutate(Rank_Original = rank(-Original_Final_Score), # Negative for descending rank
Rank_New = rank(-New_Weighted_Score))
# View the results
head(data_with_scores %>% select(Apartment_ID, Original_Final_Score, New_Weighted_Score, Rank_Original, Rank_New))
# Step 6: Output the Results
# Save the weights and updated data to a new Excel file for review
library(writexl)
write_xlsx(list(Weights = weights_df, Updated_Data = data_with_scores), "apartment_weights_and_scores.xlsx")
# End of script