Sum up counts in a data.frame grouped by multiple variables This is a snippet of the dataset I am currently working on:

&gt; 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:

&gt; 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 &lt;- matrix(0, nrow=2, ncol=2)
colnames(result) &lt;- unique(sample$name)
rownames(result) &lt;- unique(sample$sex)

for (i in 1:nrow(sample)) {
    sex &lt;- as.character(sample[i,"sex"])
    name &lt;- sample[i,"name"]
    count &lt;- sample[i,"count"]

    result[sex, name] &lt;- 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? 

Edit: 

I already tried it with aggregate, but the output is in a different format: 

&gt; aggregate(sample$count,by=list(sample$name,sample$sex),sum)
  Group.1 Group.2   x
1   Maria       m   9
2  Thomas       m  20
3   Maria       w 194
You can do this using the xtabs function! Here's how I did it using your example data:

# Create example data...
name &lt;- c("Maria", "Thomas", "Maria", "Maria", "Thomas", "Maria")
sex &lt;- c("f", "m", "m", "f", "m", "m")
count &lt;- c(97, 12, 5, 97, 8, 4)
data &lt;- data.frame("name"=name, "sex"=sex, "count"=count)

# Create table...
xtabs(formula=count~name + sex, data=data)


which gives the following output:

        sex
name       f   m
Maria    194   9
Thomas     0  20