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

如何在R中按日期分组生成Type为Farm的计算行?

用R自动生成Farm类别数据的解决方案

可以借助dplyr包快速完成这个需求,以下是具体步骤:

1. 加载依赖包

library(dplyr)

2. 准备数据(替换为你的实际数据集即可)

# 示例数据
df <- tibble(
  Apples = c(10, 20, 30, 40, 45, 40),
  Bananas = c(5, 10, 50, 30, 20, 10),
  Cherries = c(20, 30, 15, 20, 10, 60),
  Date = rep(c("Date 1", "Date 2"), each = 3),
  Type = rep(c("Store", "Car", "Home"), 2)
)

3. 计算Farm行并合并到原数据

针对指定数值列的写法(适合明确知道列名的情况)

farm_rows <- df %>%
  group_by(Date) %>%
  summarise(
    # 对每个水果列执行 Store - Car - Home 的计算
    Apples = Apples[Type == "Store"] - Apples[Type == "Car"] - Apples[Type == "Home"],
    Bananas = Bananas[Type == "Store"] - Bananas[Type == "Car"] - Bananas[Type == "Home"],
    Cherries = Cherries[Type == "Store"] - Cherries[Type == "Car"] - Cherries[Type == "Home"],
    Type = "Farm",
    .groups = "drop"
  )

# 合并原数据和新生成的Farm行
final_df <- bind_rows(df, farm_rows)

自动匹配所有数值列的写法(适合有大量水果列的场景)

如果你的数据集包含很多水果数值列,用where(is.numeric)可以自动识别所有数值型列,无需手动逐个列出:

farm_rows <- df %>%
  group_by(Date) %>%
  summarise(
    across(where(is.numeric), ~ .[Type == "Store"] - .[Type == "Car"] - .[Type == "Home"]),
    Type = "Farm",
    .groups = "drop"
  )

final_df <- bind_rows(df, farm_rows)

4. 查看结果

运行上述代码后,final_df就是你需要的包含Farm类别的完整数据集,输出格式与你期望的一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 06:22:46