在R Studio中构建新数据框并按组获取统计摘要
Grouped Summary Table for Your R Data Frame
Got it, let's break down how to create that grouped summary table you need! First, let's confirm we're working with your original data frame:
# Your original data frame df <- data.frame( number = c(3,4,5,6,7,3,5,6,7,6), group= c("red", "yellow", "green", "green", "yellow", "yellow", "red", "red", "red", "green") )
Recommended Solution: Using dplyr (Clean & Intuitive)
The dplyr package is perfect for straightforward grouped statistical operations. Here's how to use it:
- First, install and load the package (skip the install step if you already have it):
install.packages("dplyr") # Run once only library(dplyr)
- Generate your grouped summary table. I've included common useful stats, but you can adjust these to match your target table's exact requirements:
# Create grouped summary table summary_df <- df %>% group_by(group) %>% summarise( total_observations = n(), average_number = mean(number), median_number = median(number), lowest_value = min(number), highest_value = max(number), standard_deviation = round(sd(number), 2) # Rounded for readability ) %>% ungroup() # Optional: removes grouping metadata if not needed # View the final result summary_df
What this code does:
group_by(group): Groups the data into "red", "yellow", and "green" categoriessummarise(): Calculates the specified statistics for each group- The output will be a tidy data frame with one row per group and columns for each statistic.
Base R Alternative (No Packages Needed)
If you prefer not to use external packages, you can use base R's aggregate() function:
# Aggregate stats by group summary_df_base <- aggregate( number ~ group, data = df, FUN = function(x) c( count = length(x), mean = mean(x), median = median(x), min = min(x), max = max(x), sd = round(sd(x), 2) ) ) # Convert to a clean, flat data frame summary_df_base <- do.call(data.frame, summary_df_base)
Example Output Preview:
For the "red" group, you'll get:
- total_observations: 4
- average_number: 5.25
- median_number: 5.5
- lowest_value: 3
- highest_value:7
- standard_deviation:1.71
Feel free to tweak the statistic names or add/remove metrics to match your target table exactly!
内容的提问来源于stack exchange,提问作者vicky
相关产品推荐
相关产品推荐

