gpt4 book ai didi

r - 当一行出现时标记数据框中的列

转载 作者:搜寻专家 更新时间:2023-10-30 20:08:24 25 4
gpt4 key购买 nike

我有一个数据库,其中包含客户的多个订单。订单按增加的时间订购。我向您展示了其中两个客户:

data<-data.frame(ID_CLIENTE=c(rep(1,8),rep(2,8)),
PEDIDO=c("A1","A2","A3","A4","A5","A6","A7","A8", "B1","B2","B3","B4","B5","B6","B7","B8"), LABEL= c(NA, NA, "1ER_PEDIDO", NA, NA, NA, NA, NA, NA, NA, NA, NA, "1ER_PEDIDO", NA, NA, NA),
DATE= as.Date(c("2014-09-22","2014-12-16","2015-01-19","2015-03-11", "2015-05-18", "2015-10-28","2016-04-13","2016-06-09","2014-10-08","2014-10-12","2014-10-26","2014-11-06","2014-11-24","2014-12-10","2014-12-11","2015-01-12")))

> data
ID_CLIENTE PEDIDO LABEL DATE
1 1 A1 <NA> 2014-09-22
2 1 A2 <NA> 2014-12-16
3 1 A3 1ER_PEDIDO 2015-01-19
4 1 A4 <NA> 2015-03-11
5 1 A5 <NA> 2015-05-18
6 1 A6 <NA> 2015-10-28
7 1 A7 <NA> 2016-04-13
8 1 A8 <NA> 2016-06-09
9 2 B1 <NA> 2014-10-08
10 2 B2 <NA> 2014-10-12
11 2 B3 <NA> 2014-10-26
12 2 B4 <NA> 2014-11-06
13 2 B5 1ER_PEDIDO 2014-11-24
14 2 B6 <NA> 2014-12-10
15 2 B7 <NA> 2014-12-11
16 2 B8 <NA> 2015-01-12

我想标记标有“1ER_PEDIDO”的订单之前和之后的所有订单。结果数据框必须是这样的:

   ID_CLIENTE PEDIDO      LABEL       DATE
1 1 A1 BEFORE 2014-09-22
2 1 A2 BEFORE 2014-12-16
3 1 A3 1ER_PEDIDO 2015-01-19
4 1 A4 AFTER 2015-03-11
5 1 A5 AFTER 2015-05-18
6 1 A6 AFTER 2015-10-28
7 1 A7 AFTER 2016-04-13
8 1 A8 AFTER 2016-06-09
9 2 B1 BEFORE 2014-10-08
10 2 B2 BEFORE 2014-10-12
11 2 B3 BEFORE 2014-10-26
12 2 B4 BEFORE 2014-11-06
13 2 B5 1ER_PEDIDO 2014-11-24
14 2 B6 AFTER 2014-12-10
15 2 B7 AFTER 2014-12-11
16 2 B8 AFTER 2015-01-12

我应该使用 data.table 函数吗?我必须为客户的所有订单贴上标签,我必须固定客户并检查所有订单。然后,我想给他们贴上标签。

最佳答案

这是一个分两步的 data.table 方法:

library(data.table)
setDT(data)

data[data[, DATE < DATE[LABEL == "1ER_PEDIDO" & !is.na(LABEL)], by = ID_CLIENTE]$V1,
LABEL := "BEFORE"]

data[data[, DATE > DATE[LABEL == "1ER_PEDIDO" & !is.na(LABEL)], by = ID_CLIENTE]$V1,
LABEL := "AFTER"]

关于r - 当一行出现时标记数据框中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40379939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com