r - 使用 R 数据框中的条件进行计数
问题描述
我有以下DF:
Week SKU Discount(%)
1 111 5
2 111 5
3 111 0
4 111 10
1 222 0
2 222 10
3 222 15
4 222 20
1 333 5
2 333 0
3 333 0
我想有这样的结果:
Week SKU Discount(%) Duration LastDiscount
1 111 5 2 0
2 111 5 2 0
3 111 0 0 0
4 111 10 1 2
1 222 0 0 0
2 222 10 3 0
3 222 15 3 0
4 222 20 3 0
1 333 5 1 0
2 333 0 0 0
3 333 0 0 0
持续时间是 1 个 SKU 连续折扣的周数。LastDiscount 计算 SKU 上次连续折扣后的周数,前提是折扣之间的周数为 0。
解决方案
检查“持续时间”的一种选择是在按“SKU”分组后,rle
在逻辑向量上使用(运行长度编码),获取lengths
和“值”并rep
找出这些持续时间。类似地,“LastDiscount”可以通过以下方式获得获取sum
逻辑值
library(dplyr)
df1 %>%
group_by(SKU) %>%
mutate(Duration = with(rle(Discount > 0), rep(lengths*values,
lengths)),
temp = with(rle(Discount > 0), sum(values != 0)),
LastDiscount = if(temp[1] > 1) c(rep(0, n()-1), temp[1]) else 0) %>%
select(-temp)
# A tibble: 11 x 5
# Groups: SKU [3]
# Week SKU Discount Duration LastDiscount
# <int> <int> <int> <int> <dbl>
# 1 1 111 5 2 0
# 2 2 111 5 2 0
# 3 3 111 0 0 0
# 4 4 111 10 1 2
# 5 1 222 0 0 0
# 6 2 222 10 3 0
# 7 3 222 15 3 0
# 8 4 222 20 3 0
# 9 1 333 5 1 0
#10 2 333 0 0 0
#11 3 333 0 0 0
或使用data.table
library(data.table)
i1 <- setDT(df1)[, grp := rleid(Discount > 0), SKU][Discount > 0,
Duration := .N, .(grp, SKU)][,
LastDiscount := uniqueN(grp[Discount > 0]), .(SKU)][,
tail(.I[Discount > 0 & LastDiscount > 1], 1), SKU]$V1
df1[-i1, LastDiscount := 0][]
数据
df1 <- structure(list(Week = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L,
3L), SKU = c(111L, 111L, 111L, 111L, 222L, 222L, 222L, 222L,
333L, 333L, 333L), Discount = c(5L, 5L, 0L, 10L, 0L, 10L, 15L,
20L, 5L, 0L, 0L)), class = "data.frame", row.names = c(NA, -11L
))
推荐阅读
- reactjs - 在 React Redux 中管理 UI 状态
- sql - 我想检查 cnic 是否已经存在它永远不会插入 cnic
- c# - 使用 C# 从 HTML 中获取价值
- c# - 如果使用 AjaxFileUpload 工具的文件名长度过长,则显示对话框
- c# - 为什么我不能使用包含 auto 作为参数或返回类型的 DLL 中的函数?
- excel - 将唯一项目复制到其他工作表并在 Excel VBA 中删除工作表中的项目
- oracle11g - 是否有将文本包装在 ir 列中的方法
- snmp4j - SNMP4J:无法让 SNMPv3 与多个目标一起工作
- node.js - 为具有异构数组的对象创建猫鼬模式
- javascript - 查找具有样式属性的元素并更改它