如何用R计算inclass/online班级中各性别的占比?
Hey there! Let's work through this together to get the exact proportion table you're looking for. You already have the counter table with raw counts, so we can build on that with a few dplyr steps to compute the percentages and reshape the data into your desired format.
Step 1: Compute Total Counts per Class Type
First, we need to calculate the total number of students in each type (inclass/online) to use as the denominator for our proportions:
type_totals <- counter %>% group_by(type) %>% summarize(total_students = sum(n)) %>% ungroup()
This gives us a table with each class type and its total student count (39 for inclass, 111 for online).
Step 2: Calculate Proportions and Reshape the Data
Next, we'll join this total count back to our original counter table, compute the percentage for each sex within its class type, then reshape the data to have sexes as rows and class types as columns:
final_proportions <- counter %>% # Join the total counts to our raw counts left_join(type_totals, by = "type") %>% # Calculate percentage and round to 1 decimal place mutate(percentage = round(n / total_students * 100, 1)) %>% # Keep only the columns we need select(sex, type, percentage) %>% # Reshape from long to wide format pivot_wider(names_from = type, values_from = percentage)
Final Result
Running this code will give you a table that looks exactly like what you wanted:
# A tibble: 2 × 3 sex inclass online <chr> <dbl> <dbl> 1 Female 66.7 38.1 2 Male 33.3 61.9
- For inclass: Females make up ~66.7% and Males ~33.3%
- For online: Females make up ~38.1% and Males ~61.9%
Alternative Method with prop.table()
If you want to use prop.table() (since you mentioned trying it), you can first reshape the raw counts into a matrix, then compute column-wise proportions:
# Reshape counts to wide matrix format count_matrix <- counter %>% pivot_wider(names_from = type, values_from = n) %>% column_to_rownames("sex") %>% as.matrix() # Calculate column-wise proportions (margin = 2 means by column) proportion_matrix <- prop.table(count_matrix, margin = 2) * 100 # Convert back to a data frame with clean formatting final_proportions <- as.data.frame(proportion_matrix) %>% rownames_to_column("sex") %>% mutate(across(c(inclass, online), ~round(., 1)))
This will give you the same result as the first method—pick whichever feels more intuitive for you as a new R user!
内容的提问来源于stack exchange,提问作者Lydía Rósa Kims

