# Step 1: Create Household Energy Dataset

energy_data_text <- "
HouseholdSize,MonthlyConsumption,RenewablePercent,NumAppliances
2,300,20,5
4,500,30,8
1,150,10,3
5,600,40,10
3,400,25,6
2,280,15,4
4,550,35,9
1,180,5,2
3,420,28,7
5,650,45,11
2,310,18,5
4,520,33,8
3,390,22,6
2,295,16,5
4,540,36,8
1,160,8,3
5,620,42,10
3,400,25,6
2,300,20,5
4,510,32,8
1,170,7,3
5,630,43,11
3,410,26,6
2,305,19,5
4,530,34,8
3,395,23,6
1,155,6,2
5,640,44,11
2,290,17,5
4,525,33,8
"

# Convert to data frame
energy_data <- read.csv(text = energy_data_text, stringsAsFactors = FALSE)

# Look at the data
print("First few households:")
head(energy_data)

print("Summary of energy data:")
summary(energy_data)

# Step 2: Explore the Energy Data

print("Average consumption by household size:")
aggregate(MonthlyConsumption ~ HouseholdSize, data = energy_data, mean)

print("Average renewable percent by household size:")
aggregate(RenewablePercent ~ HouseholdSize, data = energy_data, mean)

# Step 3: Calculate Distances

# Calculate distances between households
energy_distances <- dist(energy_data)

# Look at the distance matrix (first 6 households)
print("Distance matrix (first 6 households):")
distance_matrix <- as.matrix(energy_distances)
print(round(distance_matrix[1:6, 1:6], 1))

# Find the most similar households
min_distance <- min(energy_distances)
print(paste("Smallest distance between any two households:", round(min_distance, 1)))

# Find the most different households
max_distance <- max(energy_distances)
print(paste("Largest distance between any two households:", round(max_distance, 1)))

# Step 4: K-Means Clustering

# Load required package
library(factoextra)

# Perform K-means clustering with 3 groups
set.seed(123)
kmeans_energy <- kmeans(energy_data, centers = 3, nstart = 25)

# See cluster assignments
print("Household cluster assignments:")
print(kmeans_energy$cluster)

# Add clusters to the data
energy_data$Cluster <- kmeans_energy$cluster

# Calculate average characteristics for each cluster
print("Average characteristics by cluster:")
cluster_summary <- aggregate(. ~ Cluster, data = energy_data, mean)
print(round(cluster_summary, 1))

# Step 5: Hierarchical Clustering

# Perform hierarchical clustering
hierarchical_energy <- hclust(energy_distances, method = "ward.D2")

# Draw the clustering tree
plot(hierarchical_energy, main = "Household Energy Clustering Tree", 
     xlab = "Households", ylab = "Distance")

# Highlight 3 main groups
rect.hclust(hierarchical_energy, k = 3, border = "red")

# Get cluster assignments
hierarchical_clusters <- cutree(hierarchical_energy, k = 3)
print("Hierarchical cluster assignments:")
print(hierarchical_clusters)
