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

如何将R语言中宽格式data.frame转换为指定长格式?

将宽格式数据转换为长格式(R语言)

原始数据结构

df <- structure(list(DATA = c("01/01/2020", "02/01/2020", "03/01/2020"), 
                     HORA = c("01:19", "02:09", "03:17"), ALT = c(0.7, 0.8, 0.9), 
                     HORA.1 = c("07:53", "08:51", "10:02"), ALT.1 = c(1.8, 1.8, 1.7), 
                     HORA.2 = c("13:41", "14:47", "16:08"), ALT.2 = c(0.8, 0.9, 0.9), 
                     HORA.3 = c("20:08", "21:08", "22:17"), ALT.3 = c(1.9, 1.8, 1.8)), 
                class = "data.frame", row.names = c(NA, -3L))

转换方法(使用tidyr包)

利用tidyr::pivot_longer函数可以快速完成宽转长操作,通过正则表达式匹配成对的列名,将其整合为对应的观测行:

# 未安装tidyr包时先执行:install.packages("tidyr")
library(tidyr)

# 执行格式转换
long_df <- df %>%
  pivot_longer(
    cols = -DATA,  # 保留日期列,转换其余所有列
    names_to = c(".value", "group"),  # .value用于提取列名前缀作为新列名
    names_pattern = "(HORA|ALT)(\\.*\\d*)"  # 正则匹配:提取HORA/ALT作为列名,忽略编号后缀
  ) %>%
  select(-group)  # 移除临时生成的group列

# 查看转换后的长格式数据
print(long_df)

转换结果

# A tibble: 12 × 3
   DATA       HORA  ALT
   <chr>      <chr> <dbl>
 1 01/01/2020 01:19   0.7
 2 01/01/2020 07:53   1.8
 3 01/01/2020 13:41   0.8
 4 01/01/2020 20:08   1.9
 5 02/01/2020 02:09   0.8
 6 02/01/2020 08:51   1.8
 7 02/01/2020 14:47   0.9
 8 02/01/2020 21:08   1.8
 9 03/01/2020 03:17   0.9
10 03/01/2020 10:02   1.7
11 03/01/2020 16:08   0.9
12 03/01/2020 22:17   1.8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:01:12