[英]condensing columns in a dataframe in R into 2 columns (index & value)
The initial dataframe is something like最初的 dataframe 类似于
ProductID Month_1 Month_2 Month_3
1 50 50 0
2 0 400 0
3 0 0 20
values for each month are listed in a separate column for each product.每个月的值都列在每个产品的单独列中。 I'm trying to condense these columns into a generic identifier & value column and am running into trouble.我正在尝试将这些列压缩为通用标识符和值列,但遇到了麻烦。
The ideal output looks something like this理想的 output 看起来像这样
ProductID Month Value
1 1 50
1 2 30
2 2 400
3 3 20
We can use pivot_longer
and filter
the elements not equal to 0我们可以使用pivot_longer
filter
不等于 0 的元素
library(dplyr)
library(tidyr)
pivot_longer(df1, cols = -ProductID, names_to = c(".value", "month"),
names_sep = "_") %>%
filter(Month != 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.