技术问询:按分组统计数据框中0的数量并绘制柱状图
Got it, let's work through this problem step by step. I'll start by recreating your dataset (filling in the truncated column with a plausible mean_Interceptions variable for completeness), then we'll count zeros across the numeric columns per group, and finally visualize the results with a bar plot.
Step 1: Recreate the Dataset
First, let's get the full data frame set up in R:
# Load required libraries library(dplyr) library(ggplot2) library(tidyr) # Create the dataset df <- data.frame( ID = c("1", "2", "3", "4", "1", "2"), Year = c("2017", "2017", "2014", "2014", "2016", "2014"), First = c("Ricardo", "Ricardo", "David", "Johnson", "Rodney", "Duron"), Last = c("Allen", "Allen", "Amerson", "Bademosi", "McLeod", "Harmon"), Team = c("ATL", "ATL", "OAK", "NE", "PHI", "NE"), Week = c(4, 4, 7, 10, 8, 8), mean_tackles = c(4, 4, 4.333333, 1, 7.333333, 1.75), mean_PassesDefended = c(0, 0, 0.333333, 0, 0.666667, 0), mean_Interceptions = c(0, 0, 1, 0, 0, 0) # Filled truncated column for completeness )
Step 2: Count Zeros by Group
We'll reshape the data to long format, filter for zeros, then count how many zeros each group has. I'm grouping by player name (combining First and Last) here, but you can easily swap this out for Team, ID, Year, or any other grouping variable you need.
# Count zeros per player zero_counts <- df %>% # Create a full player name column mutate(Player = paste(First, Last)) %>% # Reshape to long format to count zeros across all metric columns pivot_longer(cols = starts_with("mean_"), names_to = "Metric", values_to = "Value") %>% # Filter rows where the metric value is 0 filter(Value == 0) %>% # Group by player and count total zeros group_by(Player) %>% summarise(Zero_Count = n()) %>% # Sort results for cleaner visualization arrange(desc(Zero_Count))
Step 3: Plot the Bar Chart
Now let's use ggplot2 to create a clear bar chart showing the number of zeros per group:
ggplot(zero_counts, aes(x = reorder(Player, Zero_Count), y = Zero_Count)) + geom_bar(stat = "identity", fill = "#2E86AB") + labs( title = "Number of Zero Metric Values by Player", x = "Player", y = "Count of Zeros" ) + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
Customization Tips
- If you want to group by a different variable (like
Team), just change thegroup_by()argument togroup_by(Team)instead ofgroup_by(Player). - To count zeros across specific columns only (not all
mean_*columns), adjust thecolsargument inpivot_longer()to list exact columns, e.g.,cols = c(mean_tackles, mean_PassesDefended). - Tweak bar colors, titles, or axis labels by modifying the
geom_bar()fill color orlabs()/theme()arguments to match your preferences.
内容的提问来源于stack exchange,提问作者Patrick

