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

在R语言中如何将含多时间点问答的纵向数据从宽转长?

宽格式纵向数据集转长格式的R解决方案

问题背景

现有宽格式纵向数据集,包含ID、Age、Gender及分3个时间点记录的问答耗时变量(如Q1AnswerTime1),需转换为长格式:保留ID、Age、Gender,新增Time变量标记时间点,同时将对应时间点的Q1/Q2/Q3数据整理为独立列。

示例输入数据

library(tibble)

df <- tibble(
  ID = c(1, 2, 3),
  Age = c(25, 32, 28),
  Gender = c("Male", "Female", "Male"),
  Q1AnswerTime1 = c(10, 15, 12),
  Q2AnswerTime1 = c(7, 9, 8),
  Q3AnswerTime1 = c(5, 6, 4),
  Q1AnswerTime2 = c(11, 16, 13),
  Q2AnswerTime2 = c(8, 10, 9),
  Q3AnswerTime2 = c(6, 7, 5),
  Q1AnswerTime3 = c(12, 17, 14),
  Q2AnswerTime3 = c(9, 11, 10),
  Q3AnswerTime3 = c(7, 8, 6)
)

期望输出格式

dfLong <- tibble(
  ID = c(1,1,1,2,2,2, 3,3,3),
  Age = c(25,25,25,32,32, 32, 28,28,28),
  Gender = c("Male","Male","Male", "Female","Female","Female", "Male","Male","Male"),
  Q1 = c(10,11,12,15,16,17,12,13,14),
  Q2 = c(7,8,9,9,10,11,8,9,10),
  Q3 = c(5,6,7,6,7,8,4,5,6),
  Time = c(1,2,3,1,2,3,1,2,3)
)

解决方案代码

使用tidyr包的pivot_longer函数,结合正则表达式拆分列名,一步完成格式转换:

library(tidyr)
library(dplyr)

# 转换为目标长格式
dfLong <- df %>%
  pivot_longer(
    cols = starts_with("Q"),  # 选中所有Q开头的变量
    names_to = c(".value", "Time"),  # .value对应问答项(Q1/Q2/Q3),Time对应时间点
    names_pattern = "(Q\\d+)AnswerTime(\\d)"  # 正则匹配列名结构:Q+数字 + AnswerTime + 时间数字
  ) %>%
  mutate(Time = as.integer(Time))  # 将Time转为整数类型

代码说明

  1. pivot_longer核心参数:
    • cols = starts_with("Q"):精准筛选需要转换的问答耗时变量,排除ID、Age、Gender等固定变量。
    • names_to = c(".value", "Time"):指定拆分后的列名用途,.value表示将匹配到的问答项作为新列名,Time存储提取的时间点。
    • names_pattern:用正则表达式(Q\\d+)AnswerTime(\\d)拆分列名,第一组Q\\d+匹配Q1/Q2/Q3,第二组\\d匹配时间点1/2/3。
  2. mutate(Time = as.integer(Time)):将提取的时间点字符转为整数,符合输出格式要求。

运行上述代码后,即可得到与期望格式完全一致的长格式数据集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:44:57