This is a typical use of the group_by() and summarize() functions of the dplyr package. The n() function returns a count of the rows.
bdat <- data.frame(
player_name = as.factor(c("bob", "bob", "bob", "bob", "bob", "bob", "bob",
"bob", "bob", "bob", "billy", "billy", "billy",
"billy", "billy", "tom", "tom", "tom", "tom", "tom",
"aaron", "bob", "bob", "bob")),
event = as.factor(c("ball", "calledstrike", "ball", "calledstrike",
"foul", "foul", "foul", "foul", "foul",
"calledstrike", "strikeswinging", "ball", "strikeswinging",
"ball", "calledstrike", "strikeswinging",
"calledstrike", "foul", "foul", "strikeswinging", "bunt",
"calledstrike", "foul", "strikeswinging")),
pitch = as.factor(c("curveball", "fastball", "slider", "fastball",
"fastball", "fastball", "curveball", "fastball",
"curveball", "fastball", "curveball", "curveball",
"curveball", "fastball", "fastball", "fastball",
"fastball", "fastball", "curveball", "fastball",
"fastball", "curveball", "fastball", "curveball"))
)
library(dplyr)
Counts <- bdat %>% group_by(player_name, pitch) %>% summarize(N = n())
Counts
#> # A tibble: 8 x 3
#> # Groups: player_name [?]
#> player_name pitch N
#> <fct> <fct> <int>
#> 1 aaron fastball 1
#> 2 billy curveball 3
#> 3 billy fastball 2
#> 4 bob curveball 5
#> 5 bob fastball 7
#> 6 bob slider 1
#> 7 tom curveball 1
#> 8 tom fastball 4
Created on 2019-09-17 by the reprex package (v0.2.1)