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

如何用dplyr将含成对列的宽格式DataFrame转换为长格式?

使用dplyr+tidyr实现宽格式转长格式

假设你的宽格式数据遵循以下命名规则:

  • SVO1、SVA1这类列名的前缀为type(如SVO、SVA),后缀数字为stage
  • trip11、trip12这类列名的前缀为trip,后续两位数字分别对应type编码(1=SVO、2=SVA、3=OVA)和period

以下是具体实现步骤:

1. 加载依赖包

library(dplyr)
library(tidyr)

2. 示例宽格式数据

wide_df <- tibble(
  id = 1:2,
  dummy_age = c(25, 30),
  dummy_gender = c(1, 0),
  SVO1 = c(3, 4),
  trip11 = c(10, 12),
  SVO2 = c(5, 6),
  trip12 = c(15, 18),
  SVA1 = c(7, 8),
  trip21 = c(20, 22)
)

3. 转换代码

long_df <- wide_df %>%
  # 保留核心标识列和所有trip开头的数值列
  select(id, dummy_age, dummy_gender, starts_with("trip")) %>%
  # 将trip列转成长格式
  pivot_longer(
    cols = starts_with("trip"),
    names_to = "trip_col",
    values_to = "value"
  ) %>%
  # 从trip列名中提取type编码和period
  extract(
    trip_col,
    into = c("type_code", "period"),
    regex = "trip(\\d)(\\d)",
    convert = TRUE  # 自动转为数值类型
  ) %>%
  # 将type编码映射为对应的名称
  mutate(
    type = case_match(
      type_code,
      1 ~ "SVO",
      2 ~ "SVA",
      3 ~ "OVA"
    ),
    # 根据成对列规则,stage与period一一对应
    stage = period
  ) %>%
  # 调整列顺序,移除临时的type_code列
  select(id, dummy_age, dummy_gender, type, stage, period, value)

转换结果

转换后的长格式数据如下(以id=1为例):

# A tibble: 3 × 7
     id dummy_age dummy_gender type  stage period value
  <int>     <dbl>        <dbl> <chr> <int>  <int> <dbl>
1     1        25            1 SVO       1      1    10
2     1        25            1 SVO       2      2    15
3     1        25            1 SVA       1      1    20

如果你的列名规则不同(比如trip列的数字编码逻辑有差异),只需调整extract中的正则表达式和case_match的映射规则即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:05:15