You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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") 
)

The dplyr package is perfect for straightforward grouped statistical operations. Here's how to use it:

  1. First, install and load the package (skip the install step if you already have it):
install.packages("dplyr") # Run once only
library(dplyr)
  1. 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" categories
  • summarise(): 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:09:06