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

在R中使用dplyr将宽格式系数数据框重格式化为指定长表

实现方法

你可以通过dplyr搭配同生态的tidyr包完成宽表转长表的格式转换,具体操作代码如下:

首先加载依赖包:

# 若未安装依赖先执行 install.packages("tidyverse")
library(dplyr)
library(tidyr)
library(tibble)

执行转换操作:

result <- DF %>%
  # 将原始数据的行号转为显式的id列
  rownames_to_column("id") %>%
  # 宽表转长表,除id外所有列转为特征-系数的键值对
  pivot_longer(cols = -id, names_to = "raw_feature", values_to = "coeff") %>%
  # 替换特征名规则,拼接得到要求的Feature字段
  mutate(
    raw_feature = sub("\\(Intercept\\)", "intercept", raw_feature),
    Feature = paste0(id, "_", raw_feature)
  ) %>%
  # 选择输出指定列
  select(Feature, coeff)

如果使用更早版本的tidyverse工具,也可以用gather函数替代pivot_longer实现转换,对应代码如下:

result <- DF %>%
  rownames_to_column("id") %>%
  gather(key = "raw_feature", value = "coeff", -id) %>%
  mutate(
    raw_feature = sub("\\(Intercept\\)", "intercept", raw_feature),
    Feature = paste0(id, "_", raw_feature)
  ) %>%
  select(Feature, coeff)

执行上述代码后得到的result就是你需要的目标格式数据框。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:18:01