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

如何基于行值将宽格式数据转为长格式?R语言数据重塑求助

正确实现方法

用tidyverse工具链(dplyr + tidyr)可以简洁高效地完成转换,逻辑更清晰,避免循环出错:

步骤1:加载必要包

library(dplyr)
library(tidyr)

步骤2:转换宽格式为长格式(提取每个任务的选中项)

先把原数据中每个tN_choice列转成task和selected_profile两列:

long_choices <- data %>%
  pivot_longer(
    cols = starts_with("t"),  # 匹配所有以t开头的选择列
    names_to = "task",        # 列名转为task列
    values_to = "selected_profile",  # 对应值转为选中的profile
    names_prefix = "t",       # 去掉列名里的t前缀
    names_transform = list(task = as.integer)  # 把task转成整数类型
  ) %>%
  mutate(selected_profile = as.integer(selected_profile))  # 把选中的profile转成整数

步骤3:生成每个任务的3个profile行并标记choice

对每个id-task组合,生成1、2、3三个profile,然后判断当前profile是否是选中的,生成二进制的choice列:

final_df <- long_choices %>%
  group_by(id, task) %>%
  expand(profile = 1:3) %>%  # 每个组生成3个profile
  left_join(long_choices, by = c("id", "task")) %>%  # 关联选中的profile信息
  mutate(choice = ifelse(profile == selected_profile, 1, 0)) %>%  # 标记是否选中
  ungroup() %>%
  select(id, task, profile, choice)  # 保留需要的列

原代码出错原因

  • 引用了未定义的long对象,导致提取choices时直接报错
  • 循环逻辑未区分不同用户的任务选择,索引计算混乱,会把不同用户的选择混在一起赋值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:52:19