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

按多分组操作列生成新列:计算rating差值的R实现方法

按分组生成指定Rating差值列的实现方法

需求说明

现有两个数据框example_1和example_2,需按subject和event分组,根据以下规则计算rating差值:

  • 当event包含self时,计算 selfimmneg - selfrefneg
  • 当event包含other时,计算 socimmneg - socrefneg

最终输出仅保留subject、event和计算得到的rating_diff列,格式如example_solution所示。

实现代码(基于tidyverse工具集)

# 先加载所需包(未安装则先运行 install.packages("tidyverse"))
library(tidyverse)

# 处理example_2数据框,生成目标结果
example_solution <- example_2 %>%
  # 按subject和event分组,确保每组对应不同condition
  group_by(subject, event) %>%
  # 将condition转为列名,提取对应rating值
  pivot_wider(names_from = condition, values_from = rating) %>%
  # 根据event类型匹配差值计算规则
  mutate(
    rating_diff = case_when(
      str_detect(event, "self") ~ selfimmneg - selfrefneg,
      str_detect(event, "other") ~ socimmneg - socrefneg
    )
  ) %>%
  # 保留目标列并取消分组
  select(subject, event, rating_diff) %>%
  ungroup()

代码解释

  1. 分组与宽格式转换:group_by()按subject和event分组后,pivot_wider()将每组内的condition转为单独列,便于后续差值计算。
  2. 条件化差值计算:case_when()根据event中的关键词(self/other)匹配对应差值公式,自动应用计算规则。
  3. 结果整理:select()筛选目标列,ungroup()取消分组结构,得到符合要求的输出格式。

针对example_1的简化处理

若仅处理example_1(仅包含self相关condition),可简化mutate逻辑:

example_solution_1 <- example_1 %>%
  group_by(subject, event) %>%
  pivot_wider(names_from = condition, values_from = rating) %>%
  mutate(rating_diff = selfimmneg - selfrefneg) %>%
  select(subject, event, rating_diff) %>%
  ungroup()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:35:54