```{r}
library(tidyr)
library(dplyr)

seurat_object <- seurat_objects.combined
grouping_var <- "Treatment"

cells_for_all_clusters <- data.frame()
#colnames(cells_for_all_clusters) <- c("WT","THC","CBS")

## Get total number of cells per group to normalize 
control_total <-length(which(seurat_object@meta.data$Treatment=="Control"))
thc_total <- length(which(seurat_object@meta.data$Treatment=="THC"))
cbs_total <-  length(which(seurat_object@meta.data$Treatment=="CBS"))


## Iterate over each cluster
for(this_cluster in sort(unique(seurat_object@ident))){
  ## Print status for which identity is being processed
  print(paste("Working on cluster #",this_cluster,sep=""))

  this_cluster_seurat <- SubsetData(seurat_object,ident.use = this_cluster)
  
  ## Check how many groups there are
  no_of_groups <- this_cluster_seurat@meta.data %>%
    select(.dots = grouping_var) %>%
    unique() %>%
    nrow()
  
  ## Count how many cells from each group there are per cluster
  control_cells <-  length(which(this_cluster_seurat@meta.data$Treatment=="Control"))
  thc_cells <-  length(which(this_cluster_seurat@meta.data$Treatment=="THC"))
  cbs_cells <-  length(which(this_cluster_seurat@meta.data$Treatment=="CBS"))
  
  control_cells_norm <-  length(which(this_cluster_seurat@meta.data$Treatment=="Control")) / control_total
  thc_cells_norm <-  length(which(this_cluster_seurat@meta.data$Treatment=="THC")) / thc_total
  cbs_cells_norm <-  length(which(this_cluster_seurat@meta.data$Treatment=="CBS")) / cbs_total
    
  ## Add information to data frame
  
  cells_for_all_clusters <- rbind(cells_for_all_clusters,c(control_cells,thc_cells,cbs_cells,control_cells_norm,thc_cells_norm,cbs_cells_norm))
}

## Finally, name the colums as the grouping variables
colnames(cells_for_all_clusters) <- c("Control","THC","CBS","Control_normalized","THC_normalized","CBS_normalized")
write.table(cells_for_all_clusters,
            file = "Cell_counts_per_group.tsv",
            sep="\t",
            col.names = TRUE,
            row.names = FALSE)
```