如何使tibble::add_column在分组数据框中实现类似mutate的分组计算?
tibble::add_column() with Grouped Calculations (Like mutate()) Great question! The core issue here is that tibble::add_column() operates on the entire data frame as a single unit—it doesn't respect grouping contexts set up by group_by(). To get the grouped sum behavior and control exactly where your new column is inserted, you can split this into two clear steps:
Step 1: Calculate your grouped values first
First, generate a vector of grouped sums that matches the row count of your original data frame (each row gets the sum of its group's g_AD values). You can do this with a quick grouped mutate() + pull():
# Generate the grouped sum vector grouped_g_DP <- df %>% group_by(Sample) %>% mutate(temp_sum = sum(g_AD)) %>% pull(temp_sum)
Step 2: Insert the vector with add_column()
Now use add_column() to insert this vector as your new g_DP column, specifying the position with either .after or .before:
# Insert the column after the "Sample" column (or use .after = 2 for position index) df <- df %>% add_column(g_DP = grouped_g_DP, .after = "Sample")
More Compact One-Liner
If you prefer to avoid intermediate variables, you can do this all in one pipe by using the dot (.) to reference the current data frame inside add_column():
df <- df %>% add_column( g_DP = (.) %>% group_by(Sample) %>% mutate(temp_sum = sum(g_AD)) %>% pull(temp_sum), .after = "Sample" # Adjust this to your desired position )
Why This Works
By first computing the grouped sum within the group_by() context, we create a vector where every row in the same Sample group has the same sum value. add_column() then just adds this precomputed vector as a new column—no global summing involved.
If you don't need the data frame to stay grouped after this operation, you can add ungroup() to the end of your pipe to clean things up.
内容的提问来源于stack exchange,提问作者Carmen Sandoval

