This is a snippet of the dataset I am currently working on: > sample name sex count 1 Maria f 97 2 Thomas m 12 3 Maria m 5 4 Maria f 97 5 Thomas m 8 6 Maria m 4 I want to sum up the counts grouped by `name` and `sex` to finally get this data.frame: > result Maria Thomas f 194 0 m 9 20 I wrote a simple loop to iterate over the rows and sum up the counts: result <- matrix(0, nrow=2, ncol=2) colnames(result) <- unique(sample$name) rownames(result) <- unique(sample$sex) for (i in 1:nrow(sample)) { sex <- as.character(sample[i,"sex"]) name <- sample[i,"name"] count <- sample[i,"count"] result[sex, name] <- result[sex, name] + count } Is it suitable to do it this way? Are there any other ways to do it in a more elegant / shorter fashion?