0

I am trying to sum up a filtered column to count the number of occurrences. How can i sum the character data type.

bowler           dismissal_type
TS Mills         bowled
TS Mills         bowled
A Nehra          bowled
Pj cummins       bowled
TS Mills         bowled
A Nehra          bowled

I tried to sum the dismissal_type but throws me an errors saying can't sum character type

bowled <- innings%>%
 filter(dismissal_type == "bowled")%>%
 group_by(bowler)%>%
 summarize_each(bowled = sum(dismissal_type == "bowled"))%>%
 top_n()

It seems simple but can't get it done. All i want to output is:

bowler           dismissal_type  n 
TS Mills         bowled          3
A Nehra          bowled          2
Pj cummins       bowled          1
Jaap
  • 81,064
  • 34
  • 182
  • 193
Learner
  • 335
  • 3
  • 16

1 Answers1

0

You could do

# Assuming the data frame is called bowler

# Define the subset
my_subset <- bowler$dismissal_type == "bowled"
# Count the occurrences of column bowler 
my_counts <- as.integer(ave(bowler$bowler, bowler$bowler, FUN = length))
# [1] 3 3 2 1 3 2
# Initialize the column n (needed in case the subset is strict)
bowler$n <- 1L  # or any other number, na_integer, etc.
bowler$n[my_subset] <- my_counts[my_subset]
#       bowler dismissal_type n
# 1   TS Mills         bowled 3
# 2   TS Mills         bowled 3
# 3    A Nehra         bowled 2
# 4 Pj cummins         bowled 1
# 5   TS Mills         bowled 3
# 6    A Nehra         bowled 2
niko
  • 5,253
  • 1
  • 12
  • 32