1 Introduction

In order to have a deeper understanding of nutritional data, in this project, I will use the comprehensive Food and Nutrient Database for Dietary Studies (FNDDS) from the U.S. Department of Agriculture (USDA). In this database we find a wide variety of ingredients, from pure vitamin D to dairy products.

The focus of this analysis will be on the core nutrients that are present in nutritional information labels. These include protein, total fat, total carbohydrates, energy, sugars, dietary fiber, calcium, iron, potassium, sodium, cholesterol, saturated fat, monounsaturated fat, and polyunsaturated fat. This nutritional information is essential for maintaining a good health. PCA enable us to reduce the feature space while still preserving the essential variance and patterns in the nutritional data, offering a distilled yet comprehensive view of the nutritional relationships and insights.

2 Dataset

The dataset used is the Food and Nutrient Database for Dietary Studies (FNDDS) from the U.S. Department of Agriculture (USDA), which includes the nutrient values for a large quantity of ingredients. This information is valuable to have a deeper understanding of the food we consume and which ingredients may be similar to those that we prefer. The version of the dataset corresponds to the FNDDS 2019-2020, which was published in October, 2022.

2.1 Correlation plot

We can see some correlations that are in accordance with the intuition, for example energy is positively correlated with the fat content (which is the most energetic nutrient) and negatively correlated with water. We can also see correlations between similar nutrients. For example different types of saturated fatty acids (SFA) are strongly correlated between each other and correlated with the total amount of saturated fatty acids.

# Plot a heatmap of the correlation matrix using ggplot2
library(ggplot2)
library(plotly)


heatmap <- ggplot(data = as.data.frame(as.table(cor_matrix)), aes(Var1, Var2, fill = Freq)) +
  geom_tile() +
  theme_minimal() +
  labs(title = "Correlation Heatmap") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size = 6),  # Decrease font size
        axis.text.y = element_text(size = 6))  # Decrease font size

# Convert to plotly object
#interactive_heatmap <- ggplotly(heatmap)

# Render the plotly object
heatmap

In order to determine the clusterability of the dataset, Hopkins statistics has been calculated. The value of this statistic (0.9747) indicates that the dataset is highly clusterable.

Hopkins statistic: If the value of Hopkins statistic is close to 1 (far above 0.5), then we can conclude that the dataset is significantly clusterable. 1

library(factoextra)

# Assess the Hopkins statistic
hopkins_results <- get_clust_tendency(scaled_data, n = 10)

print(paste("Hopkins statistic", as.character(hopkins_results$hopkins_stat)))
## [1] "Hopkins statistic 0.974703842266244"

3 Choosing the number of clusters

The right number of clusters has been determined with the use of silhouette plots for 4 clustering methods: K-means, PAM, clara and hierarchical analysis.

library(ggplot2)
library(patchwork)
library(factoextra)

# Function to create a silhouette plot with title
create_silhouette_plot <- function(data, method, FUNcluster) {
  result <- fviz_nbclust(data, FUNcluster = FUNcluster, method = "silhouette", k.max = 10) + theme_classic()
  title <- ggtitle(paste("Silhouette Analysis - Method:", method))
  return(list(result, title))
}

# Create silhouette plots for different clustering methods
a <- create_silhouette_plot(scaled_data, "kmeans", kmeans)
b <- create_silhouette_plot(scaled_data, "pam", cluster::pam)
c <- create_silhouette_plot(scaled_data, "clara", cluster::clara)
d <- create_silhouette_plot(scaled_data, "hierarchical", hcut)

# Arrange the plots using patchwork
combined_plots <- a[[1]] + a[[2]] + b[[1]] + b[[2]] + c[[1]] + c[[2]] + d[[1]] + d[[2]]
combined_plots <- combined_plots + plot_layout(ncol = 2)

print(combined_plots)

The optimal number of clusters is the one with the highest average silhouette width. For most methods the optimal number clusters appears to be 2, with the exception of PAM where the optimal number of clusters is 10. It is worth noting that the average silhouette widths are similar for all methods for k between 4 and 10. High value for k=2 does not necessarily mean that this is the best choice for the number of clusters. Such cases have been mentioned in the literature 2, if some subset of the data is strongly separated from the rest, despite of the existence of more clusters, the separation of which is weaker.

In the case of the dataset under analysis, k=2 appears too low to lead to interesting conclusions, therefore for the further analysis k=10 has been selected. The analysis has been conducted with the use of PAM.

4 Characterization of PAM clusters

library(factoextra)
library(cluster)

# Perform PAM clustering with k=10
pam_result <- pam(scaled_data, k = 10)

# Characterize clusters
cluster_centers_pam <- pam_result$medoids
cluster_sizes_pam <- table(pam_result$clustering)
cluster_assignments_pam <- pam_result$clustering

Clusters 1, 4, 6 and 10 contain products rich in fatty acids, but with significant differences in their types.

  • Products in cluster 1 (mostly cheese and butter) contain a lot of unhealthy, saturated fatty acids.

  • In cluster 4 in addition to saturated fatty acids, products also contain a lot of sugar (they are mostly sweet, highly processed types of products, like candies and cookies).

  • Products in cluster 6 contain more unsaturated fatty acids and also some protein. They are mostly meat products, but also eggs and margarine.

  • In cluster 10 we can find different types of fats, such as lard, oils, margarine, and also products rich in fat, like nuts and seeds. They stand out due to their high content of polyunsaturated and other fatty acids and lipids (which is also the reason of high energy value) and vitamin E.

Cluster 3, similarly to cluster 6, contains meat products, however their protein content is typically higher than in cluster 6.

Cluster 5 contains products rich in sugar, such as cakes, cookies, jams and sweeteners, which seem similar to those in cluster 4, however they contain relatively less fatty acids.

Cluster 7 contains products rich in carbohydrates, such as different types of bread. Interestingly, many meat substitutes and products typically used by vegetarians, such as tofu, lentils and chickpeas, were also assigned to this cluster.

Cluster 8 contains mostly greens, such as spinach, kale and parsley, which are rich in beta-carotene, beta-cryptoxanthin, folate (vitamin B-9), lutein (antioxidant), magnesium and vitamin K.

Cluster 9 contains carrots in different forms, which comes with such nutrients as alpha and beta-carotene, beta-cryptoxanthin and vitamin A.

Most fruit and vegetables however were assigned to cluster 2, which is the biggest and most diverse cluster, containing 718 products (38% of the dataset) ranging from dairy products to drinks and ready meals.

if (!requireNamespace("DT", quietly = TRUE)) install.packages("DT")
library(DT)

# Calculate cluster means
cluster_data_pam <- cbind(scaled_data, Cluster = cluster_assignments_pam)
cluster_means_pam <- aggregate(. ~ Cluster, data = cluster_data_pam, FUN = mean)

# Filter columns where the absolute mean is greater than 1
cluster_means_pam <- round(cluster_means_pam[, colSums(abs(cluster_means_pam) > 1) > 0], 2)

# Create a data frame with cluster sizes
df_cluster_sizes <- data.frame(cluster = as.integer(names(cluster_sizes_pam)), size = as.vector(cluster_sizes_pam))

# Combine the cluster means with the cluster sizes
summary_table <- cbind(df_cluster_sizes, cluster_means_pam[, -1]) 

datatable(summary_table, 
          rownames = FALSE,
          options = list(
            scrollX = TRUE, 
            fixedColumns = list(leftColumns = 2, rightColumns = 0),
            paging = FALSE,  
            dom = 't' 
          ))

5 Cluster visualization

Due to high number of features, it is impossible to see clear separation of all clusters in one plot. The differences between clusters can be better visualized using a few plots.

fviz_cluster(pam_result, data = pam_result$data, geom = "point", pointsize = 2)

In the plot below, we can observe differences between clusters 1, 3 and 4. We can see that products in cluster 1 and 3 have more proteins than in cluster 4, and products in cluster 4 have more sugar than the other two clusters. Clusters 1 and 3 differ mainly in the amount of saturated fatty acids.

library(rgl)
library(viridis)

set.seed(123)
colors <- sample(turbo(8, alpha=1))

selected_axes <- c(14, 38, 51) 
selected_clusters <- c(1, 3, 4)

filter_by_clusters <- pam_result$clustering %in% selected_clusters

# Create a color vector mapped to the clustering result
color_map <- colors[pam_result$clustering[filter_by_clusters]]

# 3D plot
plot3d(scaled_data[filter_by_clusters, selected_axes], col=color_map)

# Adding a legend in 3D plot
legend3d("topright", legend=unique(pam_result$clustering[filter_by_clusters]), fill=unique(color_map), cex=0.6)


rglwidget()

In the plot below, we can see the clusters 4, 5 and 7, which have in common certain types of baked products like pastries. However, we can see that products from cluster 7 despite high contents of carbohydrates do not contain as much sugar as products in the other two clusters. Products in cluster 4 contain more saturated fatty acids in comparison to products in cluster 5. Some outliers are visible with higher content of saturated fatty acids in cluster 4.

library(rgl)

selected_axes <- c(4, 14, 51) 
selected_clusters <- c(4, 5, 7) 

filter_by_clusters <- pam_result$clustering %in% selected_clusters

# Create a color vector mapped to the clustering result
color_map <- colors[pam_result$clustering[filter_by_clusters]]

# 3D plot
plot3d(scaled_data[filter_by_clusters, selected_axes], col=color_map)

# Adding a legend in 3D plot
legend3d("topright", legend=unique(pam_result$clustering[filter_by_clusters]), fill=unique(color_map), cex=0.6)


rglwidget()

6 Summary

This research provides a comprehensive analysis of ingredients clustering based on their nutritional content. It includes comparing several clustering methods, identifying optimal cluster numbers and characterizing each cluster by its predominant nutritional attributes. Notably, clusters varied significantly, from those high in unhealthy saturated fats and sugars to those abundant in healthy unsaturated fats and proteins. The analysis revealed meaningful clusters that could inform dietary choices and be used for nutritional recommendations. The findings highlight the complexity and diversity of nutritional profiles across different ingredients. Future analysis could include clustering for branded food items commonly found in stores, which are more familiar to consumers.


  1. Assessing Clustering Tendency documentation↩︎

  2. Hennig, C., Lin, C.J., 2015. Flexible parametric bootstrap for testing homogeneity against clustering and assessing the number of clusters. Statistics and Computing 25, 821–833.↩︎