Your problem is quiet, and like Marcus said, dplyr
can handle it. But I found his solution not too general.
The following code counts occurrences of x
in each group of y
(note that I slightly altered its matrix to give a count greater than 1).
df <-
data.frame(
x = c('A', 'B', 'A','C','B','A', 'A'),
y = c(1,1,2,1,2,3,1)
)
df %>%
group_by(y, x) %>%
count()
Resulting in:
# A tibble: 6 x 3
# Groups: y, x [6]
y x n
<dbl> <fctr> <int>
1 1 A 2
2 1 B 1
3 1 C 1
4 2 A 1
5 2 B 1
6 3 A 1
Another way to count the elements of a group is by using the function n()
within a summarise
:
df %>%
group_by(y, x) %>%
summarise(contagem = n())
The result is the same as the previous one.
If you need to separate the table into several smaller tables according to the values of y, you can do so:
df %>%
group_by(y, x) %>%
count %>%
split(.$y)
Resulting in a list of tibbles
(easily convertible to data frames
):
$`1`
# A tibble: 3 x 3
# Groups: y, x [3]
y x n
<dbl> <fctr> <int>
1 1 A 2
2 1 B 1
3 1 C 1
$`2`
# A tibble: 2 x 3
# Groups: y, x [2]
y x n
<dbl> <fctr> <int>
1 2 A 1
2 2 B 1
$`3`
# A tibble: 1 x 3
# Groups: y, x [1]
y x n
<dbl> <fctr> <int>
1 3 A 1
Just to understand, you want to group the data by y and count the values of x within each group, correct?
– Guilherme Marthe