使用aggregate和mutate计算两列均值报错问题(更新版)
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).
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)
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
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 eachunit+testnumpair.
内容的提问来源于stack exchange,提问作者icedcoffee

