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

使用aggregate和mutate计算两列均值报错问题(更新版)

Why Your Code Is Throwing an Error

The problem with your code is that aggregate() returns an entire data frame, but mutate() is designed to add new columns where each row contains a single scalar value. You can't store a full data frame inside a column of another data frame, which is why you're seeing the "unsupported class data.frame" error.

Instead of trying to add summary values to every row with mutate(), you need to collapse your data into grouped summary rows using summarize() (paired with group_by() to define your groups).

Correct Solution Using dplyr

Since you're already using the pipe operator (%>%), let's stick with dplyr for a clean, readable solution. You want to group by both unit and testnum (since your desired output groups these two together), then calculate the mean for length and width:

library(dplyr)

# Generate the summary data frame
df_summary <- df %>%
  group_by(unit, testnum) %>%
  summarize(
    average_length = mean(length),
    average_width = mean(width),
    .groups = "drop" # Removes grouping after summarization
  )

# Optional: Rename "testnum" to "test" to match your desired output
df_summary <- df_summary %>% rename(test = testnum)
Result

Running this code will give you exactly the output you want:

unit test average_length average_width
1 unit1   t2      4.666667      4.000000
2 unit2   t1      4.285714      5.142857
Key Difference to Remember
  • mutate(): Adds new columns to your existing data frame, keeping all original rows. Each new column value is calculated per-row or per-group but stays aligned with the original rows.
  • summarize(): Collapses each group into a single summary row, which is exactly what you need here to get aggregated means for each unit + testnum pair.

内容的提问来源于stack exchange,提问作者icedcoffee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:42:39