在R语言中对两个数据表对应Task的FC值求和生成新表C
Hey there! Let's figure out how to generate your desired data frame C by summing the FC values for matching Task entries across data frames A and B. I'll walk you through two straightforward approaches in R:
This method uses built-in R functions, no extra packages needed:
First, we'll combine the two data frames into a single one using rbind() (since they have identical column structures):
# Combine A and B into a single data frame combined_data <- rbind(A, B)
Next, we'll use aggregate() to group by the Task column and sum the corresponding FC values:
# Calculate summed FC per Task C <- aggregate(FC ~ Task, data = combined_data, FUN = sum)
If you want to ensure the Task order matches your desired output exactly (a → b → c), you can reorder the rows:
# Reorder to match your target sequence C <- C[match(c("a", "b", "c"), C$Task), ]
Running print(C) will give you exactly the result you want:
print(C) # Task FC # 1 a 120 # 2 b 170 # 3 c 230
If you prefer a more readable, pipeline-based workflow, the dplyr package (part of the tidyverse) is perfect for this. First, install it if you haven't already:
install.packages("dplyr")
Then load the package and use a pipeline to combine, group, and summarize:
library(dplyr) # Create data frame C in one readable step C <- bind_rows(A, B) %>% group_by(Task) %>% summarize(FC = sum(FC)) %>% filter(Task %in% c("a", "b", "c")) %>% # Optional: keep only the tasks you need ungroup()
Let's break this down:
bind_rows(A, B): Combines the two data frames (works even if columns are in different order, unlikerbind())group_by(Task): Groups the combined data by the Task columnsummarize(FC = sum(FC)): Calculates the sum of FC for each groupfilter(Task %in% c("a", "b", "c")): Optional step to exclude tasks d and e from data frame Aungroup(): Removes the grouping structure (good practice for clean data frames)
Again, printing C will give your desired output.
内容的提问来源于stack exchange,提问作者Jenny Pham

