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

在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:

Using Base 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
Using dplyr (Tidyverse Approach)

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, unlike rbind())
  • group_by(Task): Groups the combined data by the Task column
  • summarize(FC = sum(FC)): Calculates the sum of FC for each group
  • filter(Task %in% c("a", "b", "c")): Optional step to exclude tasks d and e from data frame A
  • ungroup(): Removes the grouping structure (good practice for clean data frames)

Again, printing C will give your desired output.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:14:16