首页 > 解决方案 > 将 R 中数据框中的列压缩为 2 列(索引和值)

问题描述

初始数据框类似于

ProductID  Month_1   Month_2    Month_3
1           50       50         0
2           0        400        0    
3           0        0          20  

每个月的值都列在每个产品的单独列中。我正在尝试将这些列压缩为通用标识符和值列,但遇到了麻烦。

理想的输出看起来像这样

ProductID  Month   Value 
1           1       50
1           2       30
2           2       400  
3           3       20   

标签: r

解决方案


我们可以使用不等于0的pivot_longer元素filter

library(dplyr)
library(tidyr)
pivot_longer(df1, cols = -ProductID, names_to = c(".value", "month"), 
        names_sep = "_") %>% 
  filter(Month != 0) 

推荐阅读