R DataFrame列转行操作:列名转为Type列值,对应值存入Count列
R语言宽表转长表实现方案
方法1:使用tidyverse套件(推荐)
library(tidyverse) # 转换宽表为长表,同时修正原列名拼写错误 Unp_long <- Unp %>% pivot_longer( cols = -Week, # 排除Week列,其余列都做转换 names_to = "Type", # 原列名存储到Type列 values_to = "Count" # 原数值存储到Count列 ) %>% # 修正原累计目标列的拼写错误(Cumilative→Cumulative) mutate(Type = recode(Type, "Cumilative target" = "Cumulative target"))
转换后前6行输出示例:
# A tibble: 40 × 3 Week Type Count <date> <chr> <dbl> 1 2019-01-07 Target 5 2 2019-01-07 Cumulative target 5 3 2019-01-14 Target 8 4 2019-01-14 Cumulative target 13 5 2019-01-21 Target 15 6 2019-01-21 Cumulative target 28
方法2:基础R实现(无需额外安装包)
Unp_long <- reshape( Unp, idvar = "Week", # 主键列 varying = list(c("Target", "Cumilative target")), # 需要转换的列 v.names = "Count", # 数值列名 timevar = "Type", # 类型列名 times = c("Target", "Cumulative target"), # Type列的取值 direction = "long" # 转换方向为长表 ) rownames(Unp_long) <- NULL # 重置行号
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

