Following on from my earlier post on creating a table of ICD codes in R, here is how I am currently counting these codes and storing the codes in a dataframe: Firstly create a dataframe to store the results in: hosp_count <- as.data.frame(matrix(ncol=length(icd_codes))) names(hosp_count) <- names(icd_codes) Counting Occurences: Then start to loop through your dataset with