r - 将 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
解决方案
我们可以使用不等于0的pivot_longer
元素filter
library(dplyr)
library(tidyr)
pivot_longer(df1, cols = -ProductID, names_to = c(".value", "month"),
names_sep = "_") %>%
filter(Month != 0)
推荐阅读
- paypal - 是否有使用 REST API V2 的 PayPal SDK
- google-chrome - Chrome 扩展网页检查器
- mysql-workbench - 连接失败 - AWS RDS 和 mySQL Workbench
- android - 如果我在本地存储和检索数据,是否需要后台线程?
- asp.net-mvc - 单个 MVC APP 中的 Azure AD 和身份框架
- php - 自定义 Woocommerce 电子邮件:获取产品缩略图和价格
- python - 调用特定函数的函数列表
- java - 是不是不可能在后台有一个代码,每 24 小时都会调用一次?
- kotlin - 在 kotlin 中从 GSON 生成对象时不调用数据类初始化函数
- c - 练习使用 strace 确定源代码行为