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

R语言长格式调研面板数据转换为宽格式的方法咨询

R长表转宽表实现方案

基础实现(适配示例场景)

你不需要额外新增Survey Number列即可完成转换,使用tidyverse套件的pivot_wider函数可以一步实现需求,代码如下:
首先加载依赖包:

library(tidyverse)

导入原始数据(你提供的dput结构直接运行即可生成数据框):

# 原始数据构造
df <- structure(list(survey_unique_id = c(2816790L, 2816790L, 2816790L, 
2585861L, 2585861L, 214733L, 214733L, 214733L, 224481L, 224481L, 
224481L), user_id = c(623333L, 623333L, 623333L, 623333L, 623333L, 
700200L, 700200L, 700200L, 700200L, 700200L, 700200L), 
survey_completion_date = c("3/3/2021 16:39", "3/3/2021 16:39", 
"3/3/2021 16:39", "1/29/2021 22:14", "1/29/2021 22:14", "11/27/2017 19:02", 
"11/27/2017 19:02", "11/27/2017 19:02", "12/19/2017 21:02", 
"12/19/2017 21:02", "12/19/2017 21:02"), survey_id = c(1L, 1L, 
1L, 4L, 4L, 1L, 1L, 1L, 9L, 9L, 9L), question_id = c(1L, 2L, 
3L, 6L, 7L, 1L, 2L, 3L, 19L, 20L, 21L), question_score = c(7L, 
7L, 9L, 13L, 5L, 18L, 12L, 15L, 11L, 12L, 12L)), class = 
"data.frame", row.names = c(NA, -11L))

执行转换:

df_wide <- df %>% 
  pivot_wider(
    id_cols = user_id,
    names_from = c(survey_id, question_id),
    values_from = question_score,
    names_glue = "survey_{survey_id}_question_{question_id}_score"
  )

运行后得到的df_wide和你给出的预期输出完全一致。

扩展场景:存在同一用户同一份调研多次作答的处理

如果你的全量数据中存在同一个用户参与同一份调研多次的情况,才需要新增作答次数字段,代码调整如下:

df_wide_with_attempt <- df %>% 
  # 按用户、调研、问题分组,标记作答次数
  group_by(user_id, survey_id, question_id) %>% 
  mutate(attempt_num = row_number()) %>% 
  ungroup() %>% 
  pivot_wider(
    id_cols = user_id,
    # 把作答次数也加入列名构成维度
    names_from = c(survey_id, question_id, attempt_num),
    values_from = question_score,
    names_glue = "survey_{survey_id}_question_{question_id}_attempt_{attempt_num}_score"
  )

性能说明

tidyverse的函数针对大数据量做了优化,只要你的内存可以容纳原始数据,就可以正常完成转换,不需要借助Excel处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:15:04