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

如何在R中将单行多变量数据转换为长格式表格?

解决方案

用R的tidyverse工具包可以轻松完成这个格式转换,核心用到pivot_longer(宽表转长表)和separate(拆分合并列名)两个函数:

  1. 先加载所需包:
library(tidyverse)
  1. 假设你的原始数据框为df(如果已有数据,直接替换成你的数据框名即可):
df <- tibble(
  thurs_brkf_banana = 1.2,
  thurs_brkf_orange = 3.7,
  thurs_lun_turkey = 8.4,
  thurs_lun_cheese = 2.5,
  thurs_din_spaghetti = 4.5,
  thurs_din_bread = 1.7
)
  1. 执行格式转换:
df_long <- df %>%
  pivot_longer(
    cols = everything(),       # 选中所有列进行转长操作
    names_to = "combined",     # 将原列名存入临时列`combined`
    values_to = "rr"           # 将原数值存入`rr`列
  ) %>%
  separate(
    col = combined,            # 拆分临时列`combined`
    into = c("day", "meal", "food"),  # 拆分后生成指定的三列
    sep = "_"                  # 按下划线作为拆分分隔符
  )

运行后df_long就是你需要的长格式tibble,结构和你给出的目标格式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:53:30