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

在R中聚合与重塑数据框:将长数据框转为宽数据框

把长格式DataFrame转为宽格式的R实现方案

刚好处理过类似的长转宽需求,给你两种实用的方法,都是R生态里常用的工具,完美匹配你要的输出格式:

方法1:使用tidyr的pivot_wider(推荐,tidyverse生态)

首先先确认你的示例数据结构(先跑一遍你给的代码生成数据):

# 生成示例数据
df <- data.frame(
  date = rep(seq(as.Date("1990/1/1"), as.Date("1999/1/1"), "years"),10),
  price = seq.int(1, 100),
  type = c(rep("str",10), rep("str2",10), rep("chr",10), rep("chr2",10), 
           rep("num",10), rep("num2",10), rep("posix",10), rep("posix2",10), 
           rep("date",10), rep("date2",10))
)

接下来用tidyr::pivot_wider直接转换,参数完全对应你的需求:

  • id_cols = type:把type作为行标识
  • names_from = date:把date的唯一值作为列名
  • values_from = price:用price的值填充对应单元格

代码如下:

# 加载tidyverse(或者单独加载tidyr)
library(tidyverse)

# 长转宽
wide_df <- df %>% 
  pivot_wider(
    id_cols = type,
    names_from = date,
    values_from = price
  )

# 查看结果
print(wide_df)

运行后输出的格式完全符合你的要求:type作为第一列,每个日期作为后续列,每行对应一个type的所有日期价格,示例片段如下:

# A tibble: 10 × 11
   type   `1990-01-01` `1991-01-01` `1992-01-01` ...
   <chr>         <int>        <int>        <int> ...
 1 str               1            2            3 ...
 2 str2             11           12           13 ...
 3 chr              21           22           23 ...
 ...
 9 date             81           82           83 ...
10 date2            91           92           93 ...

方法2:使用reshape2的dcast(传统方法)

如果你习惯用reshape2包,也可以用dcast函数实现,逻辑类似:

# 加载reshape2
library(reshape2)

# 长转宽
wide_df_dcast <- dcast(df, type ~ date, value.var = "price")

# 查看结果
print(wide_df_dcast)

输出格式和第一种方法一致,只是返回的是标准data.frame而非tibble,根据你的习惯选择即可。

小提示

如果需要调整日期列名的格式(比如去掉前导零),可以先把date列转成自定义格式的字符,再进行转换:

df <- df %>% 
  mutate(date = format(date, "%Y-%-m-%-d")) # 去掉月份和日期的前导零

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:11:22