Q:

How can I count occurences of different integer values (in a particular column) for rows with different factor values(another column)?

I have a dataframe which looks something like this:
My_Data = data.frame(name = rep(LETTERS[1:10],3), number = sample(0:3,30, replace=TRUE)

    name number
1     A      3
2     B      3
3     C      0
4     D      3
5     E      2
6     F      2
7     G      2
8     H      2
9     I      1
10    J      3
11    A      1
12    B      2
13    C      0
14    D      1
15    E      3
16    F      0
17    G      2
18    H      2
19    I      2
20    J      2
21    A      0
22    B      1
23    C      3
24    D      0
25    E      2
26    F      0
27    G      1
28    H      1
29    I      3
30    J      0

Now I would like to get a dataframe which has columns for each of the possible values in the number column and the count of the occurences for each of the number values with respect to each value in the name column
    name number_0  number_1   number_2  number_3
1     A      1         1        0         1
2     B      0         1        1         1
3     C      2         0        0         1
4     D      1         1        0         1
5     E      0         0        2         1
6     F      2         0        1         0
7     G      0         1        2         0
8     H      0         1        2         0
9     I      0         1        1         1  
10    J      1         0        1         1

How can I do that?
Thanks!
Edit: I am not looking for a conversion to the wide format. I am looking for a way to count occurences for each of the possible values.

A:

You can also use xtabs() function.
xtabs(~My_Data$name + My_Data$number)

A:

We could get the count and then spread to 'wide' format
library(dplyr)
library(tidyr)
My_Data %>% 
     count(name, number) %>% 
     mutate(number = paste('number', number, sep='_')) %>% 
     spread(number, n, fill = 0)
# A tibble: 10 x 5
#    name number_0 number_1 number_2 number_3
# * <chr>    <dbl>    <dbl>    <dbl>    <dbl>
# 1     A        1        1        0        1
# 2     B        0        1        1        1
# 3     C        2        0        0        1
# 4     D        1        1        0        1
# 5     E        0        0        2        1
# 6     F        2        0        1        0
# 7     G        0        1        2        0
# 8     H        0        1        2        0
# 9     I        0        1        1        1
#10     J        1        0        1        1

A:

Try also:
table(My_Data)

or, if you need a data.frame:
as.data.frame.matrix(table(My_Data))

