我试图总结一个过滤的列以计算出现的次数。如何求和字符数据类型。
bowler dismissal_type
TS Mills bowled
TS Mills bowled
A Nehra bowled
Pj cummins bowled
TS Mills bowled
A Nehra bowled
我试图对dismissal_type
求和,但抛出一个错误,提示不能对字符类型求和
bowled <- innings%>%
filter(dismissal_type == "bowled")%>%
group_by(bowler)%>%
summarize_each(bowled = sum(dismissal_type == "bowled"))%>%
top_n()
这似乎很简单,但无法完成。我要输出的是:
bowler dismissal_type n
TS Mills bowled 3
A Nehra bowled 2
Pj cummins bowled 1
答案 0 :(得分:0)
你可以做
# 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