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

如何在R的dataframe中对指定列执行unpivot逆透视操作

你需要实现的是宽表转长表操作,R中常用的实现方案如下:

方法1:使用tidyverse系列的pivot_longer()(最推荐)

属于tidyverse生态的标准长宽转换函数,语法简洁易读:

# 加载依赖包
library(tidyr)
library(dplyr)

# 假设你的原始数据框名为df
df_long <- df %>%
  pivot_longer(
    cols = starts_with("M1."), # 选中所有M1.开头的待合并列,也可直接写c("M1.1","M1.2","M1.3")
    names_to = NULL, # 无需保留原M1.1/1.2/1.3的列名
    values_to = "M1" # 合并后的新值列命名为M1
  )

方法2:使用reshape2包的melt()

是较早的长/宽表转换工具,兼容性较好:

# 加载依赖包
library(reshape2)

df_long <- melt(
  df,
  id.vars = c("id", "M2", "M3", "M4", "M5", "M6"), # 指定需要重复保留的列
  measure.vars = c("M1.1", "M1.2", "M1.3"), # 指定需要合并拉长的列
  value.name = "M1" # 合并后的值列名
)
# 移除默认生成的、存储原列名的variable列
df_long$variable <- NULL

方法3:基础R原生reshape()

无需安装任何第三方包,直接可用:

df_long <- reshape(
  df,
  varying = c("M1.1", "M1.2", "M1.3"),
  v.names = "M1",
  idvar = c("id", "M2", "M3", "M4", "M5", "M6"),
  direction = "long",
  times = NULL
)
# 清除转换后自动生成的行名
rownames(df_long) <- NULL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:54:00