在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
相关产品推荐
相关产品推荐

