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

如何在R语言中筛选合并两个DataFrame,生成含双选项与选择标记的结果?

解决方案:重塑调查数据为选项行格式

我明白你想要的是把每个受访者看到的玫瑰、郁金香两个选项拆分成独立行,同时用字段标记该选项是否被选中的格式,下面是基于tidyverse工具链的完整解决方案:

步骤1:加载依赖包

首先确保你已经安装并加载了tidyverse包,它包含我们需要的dplyr、tidyr等工具:

library(tidyverse)

步骤2:处理颜色组合数据(df1)

我们先给df1的每个颜色组合添加唯一标识,然后把每个组合拆分为玫瑰和郁金香两个独立的选项行,同时整理颜色信息:

# 处理df1:生成每个组合对应的玫瑰/郁金香选项
df1_options <- df1 %>%
  mutate(combo = paste0("v", row_number())) %>% # 为每个颜色组合添加v1-v16的唯一标识
  pivot_longer(
    cols = -combo,
    names_to = c("flower_type_num", ".value"),
    names_pattern = "V(\\d)" # 从V1/V2/V3/V4中提取数字后缀
  ) %>%
  mutate(
    # 根据数字后缀区分玫瑰(V1/V2)和郁金香(V3/V4)
    flower_type = case_when(
      flower_type_num %in% c("1", "2") ~ "rose",
      flower_type_num %in% c("3", "4") ~ "tulip"
    ),
    # 把同一种花的两个颜色合并为一个字段,方便阅读
    color_pair = paste(V1, V2)
  ) %>%
  select(combo, flower_type, color_pair) %>%
  distinct() # 每个组合保留玫瑰、郁金香各一行

步骤3:处理受访者选择数据(df2)

把df2从宽格式转换为长格式,提取每个受访者的有效选择,并把数字标记转换为对应的花朵类型:

# 处理df2:提取受访者的有效选择
df2_responses <- df2 %>%
  pivot_longer(
    cols = -respondentID,
    names_to = "combo",
    values_to = "selected_flower_code"
  ) %>%
  filter(!is.na(selected_flower_code)) %>% # 去掉未作答的记录
  mutate(
    # 把数字1/2转换为对应的花朵类型:1=玫瑰,2=郁金香
    selected_flower = case_when(
      selected_flower_code == 1 ~ "rose",
      selected_flower_code == 2 ~ "tulip"
    )
  )

步骤4:关联数据并生成最终格式

将两个数据集关联,为每个受访者生成两行记录(对应两个选项),并添加selected字段标记是否选中:

# 关联数据,生成最终格式
final_result <- df1_options %>%
  full_join(df2_responses, by = "combo") %>%
  mutate(
    # 标记当前选项是否被选中:匹配则为1,否则为0
    selected = ifelse(flower_type == selected_flower, 1, 0),
    # 把未选中的选项(NA)统一标记为0
    selected = replace_na(selected, 0)
  ) %>%
  select(respondentID, combo, flower_type, color_pair, selected) %>%
  arrange(respondentID, combo) # 按受访者ID和组合ID排序

结果示例

运行上述代码后,你会得到如下格式的数据(展示前6行):

respondentID combo flower_type color_pair selected
1            1    v1        rose    red blue        0
2            1    v1       tulip green yellow        1
3            2    v6        rose    red blue        0
4            2    v6       tulip  green black        1
5            3    v5        rose    red blue        1
6            3    v5       tulip turqoise yellow        0

这个格式完全符合你的需求:

  • 每个受访者对应两行记录,分别对应他们看到的玫瑰和郁金香选项
  • selected字段用1/0明确标记该选项是否被选中
  • color_pair直接展示了该花朵的两个颜色组合,便于后续分析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:50:42