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

如何用Base R的reshape()函数将数据转换为宽格式?

用Base R的reshape()实现数据转换

先看你的原始数据结构:

month <- c("jan", "feb", "mar", "apr")
hours <- c(40, 40, 35, 37)
days <- c(31, 28, 31, 30)
dat <- data.frame(month, hours, days)

要得到你要的格式,分两步用reshape()函数就能完成:

第一步:把宽格式转成长格式

先将hours和days合并成一个分类列,同时把对应数值整合到一列:

# 转成长格式
long_dat <- reshape(
  dat,
  direction = "long",  # 指定转换方向为长格式
  varying = c("hours", "days"),  # 需要整合的列
  v.names = "value",  # 数值列的名称
  timevar = "metric",  # 用来区分hours和days的分类列名称
  times = c("hours", "days")  # 分类列的具体取值
)

转换后的long_dat结构如下:

month metric value id
hours.jan   jan  hours    40  1
hours.feb   feb  hours    40  2
hours.mar   mar  hours    35  3
hours.apr   apr  hours    37  4
days.jan    jan   days    31  1
days.feb    feb   days    28  2
days.mar    mar   days    31  3
days.apr    apr   days    30  4

第二步:把长格式转成目标宽格式

以metric为分组依据,将month的不同取值转为列:

# 转成目标宽格式
wide_dat <- reshape(
  long_dat,
  direction = "wide",  # 指定转换方向为宽格式
  idvar = "metric",  # 作为行的分组列
  timevar = "month",  # 要转为列的分组列
  v.names = "value"  # 填充到单元格的数值列
)

# 整理行名和列名,去掉冗余部分
rownames(wide_dat) <- wide_dat$metric
wide_dat <- wide_dat[, -1]
colnames(wide_dat) <- gsub("value\\.", "", colnames(wide_dat))

最终得到的wide_dat就是你要的结构:

jan feb mar apr
hours   40  40  35  37
days    31  28  31  30

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:13:18