【发布时间】:2020-04-14 00:39:23
【问题描述】:
我正在尝试获取产品更改的正确实例计数并且正在苦苦挣扎。我觉得这应该很容易,但是对于我的生活,我今天无法弄清楚,这让我发疯了。
所以下面我有一些针对虚拟数据的示例代码:
library(tidyverse)
library(openxlsx)
library(olapR)
library(janitor)
file_path <- "C:\\Users\\user_name\\Desktop\\R_Question.xlsx"
df_file <- read.xlsx(file_path)
df_file <- df_file %>%
clean_names() %>%
mutate(actual_result = if_else((lag(product_type) == product_type &
lag(claim_type) == claim_type &
lag(date) != date),
item_count + 1,
item_count)
) %>%
replace(is.na(.), 1) %>%
mutate(actual_result = str_c("A", actual_result))
df_file
产生:
date order product claim_type item_count desired_result actual_result
2019-12-01 QN123456 Jacket Alteration 1 A1 A1
2019-12-07 QN123456 Jacket Alteration 1 A2 A2
2019-12-11 QN123456 Pants Alteration 1 A1 A1
2019-12-13 QN123456 Pants Alteration 1 A2 A2
2019-12-18 QN123456 Pants Alteration 1 A3 A2
2019-12-19 QN123456 Pants Alteration 1 A4 A2
除了最后一列之外的所有内容都是读入的文件的一部分。最后一列是使用 mutate 添加的。我试图从 mutate to = 期望的结果列中获取实际结果,但我一直在“实际结果”列结束。
我尝试过使用 purr::map() + 函数以及 for 循环,但最终得到的结果与“actual_result”列相同。
我也尝试使用 cumsum(item_count) 代替 item_count + 1 但这不是我想要的,它会产生:
date order product claim_type item_count desired_result actual_result
2019-12-01 QN123456 Jacket Alteration 1 A1 A1
2019-12-07 QN123456 Jacket Alteration 1 A2 A2
2019-12-11 QN123456 Pants Alteration 1 A1 A1
2019-12-13 QN123456 Pants Alteration 1 A2 A4
2019-12-18 QN123456 Pants Alteration 1 A3 A5
2019-12-19 QN123456 Pants Alteration 1 A4 A6
... 这很接近,但不是我需要的
有什么想法吗?
谢谢!
【问题讨论】: