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

如何用stats::reshape()替代tidyr::pivot_longer()实现宽表转长表?

使用stats::reshape()替代tidyr::pivot_longer()实现宽转长数据

想要用stats::reshape()替代tidyr::pivot_longer()将宽格式数据转换为长格式,具体操作如下:

原始示例代码(tidyr实现)

library("tidyr")
set.seed(42)
n = 10
df_wide = data.frame(A = runif(n), B = runif(n), C = runif(n),
                     group = as.factor(sample(1:3, size = n, replace = TRUE)))
head(df_wide)
#           A          B         C group
# 1 0.9148060 0.4577418 0.90403139     2
# 2 0.9370754 0.7191123 0.13871017     3
# 3 2.861395 0.9346722 0.98889173     2

df_long = pivot_longer(df_wide, cols = 1:3, names_to = "column", values_to = "value")
head(df_long)
#   group column value
# 1 2     A      0.915
# 2 2     B      0.458
# 3 2     C      0.904

使用stats::reshape()的替代方案

以下是与上述tidyr代码效果最接近的stats::reshape()实现,唯一区别是reshape()会自动生成行名,我们可以通过移除自动添加的id列来对齐结果:

df_long = reshape(df_wide, direction = "long", varying = 1:3, v.names = "value",
                  timevar = "column", times = c("A", "B", "C")) |>
  subset(select = -id)

参数说明:

  • direction = "long":指定转换方向为长格式
  • varying = 1:3:指定需要从宽转长的目标列(对应示例中的A、B、C列)
  • v.names = "value":定义长格式中存储数值的列名
  • timevar = "column":定义长格式中存储原宽列名的列名
  • times = c("A", "B", "C"):为转换后的列名标签指定具体值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:55:01