为Sankey Diagram构建事务数据

问题描述 投票:1回答:1

Sankey图有很多软件包。但是,这些软件包假设数据已经结构化。我正在查看一个交易数据集,我想在时间序列中提取第一批产品。假设已经订购了时间序列。

这是数据集:

structure(list(date = structure(c(1546300800, 1546646400, 1547510400, 1547596800, 1546387200, 1546646400, 1546732800), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
               client = c("a", "a", "a", "a", "b", "b", "b"),
               product = c("butter", "cheese", "cheese", "butter", "milk", "garbage bag", "candy"),
               qty = c(2, 3, 4, 1, 3, 4, 6)), row.names = c(NA, -7L), class = c("tbl_df", "tbl", "data.frame")) 

这是所需的输出:

r plyr sankey-diagram
1个回答
0
投票

这是我的建议:

dt <-structure(list(date = structure(c(1546300800, 1546646400, 1547510400, 1547596800, 1546387200, 1546646400, 1546732800), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
               client = c("a", "a", "a", "a", "b", "b", "b"),
                          product = c("butter", "cheese", "cheese", "butter", "milk", "garbage bag", "candy"),
               qty = c(2, 3, 4, 1, 3, 4, 6)), row.names = c(NA, -7L), class = c("tbl_df", "tbl", "data.frame"))

library(data.table)
library(stringr)
dt <- as.data.table(dt)
dt[, From:=shift(product,type = "lag"), by=client]
dt <- dt[!is.na(From)]

setnames(dt, "product", "To")
dt <- dt[From!=To]
setcolorder(dt, c("client", "From", "To", "qty"))
dt[, comp:=paste0(sort(c(From, To)), collapse = "_"), by=seq_len(nrow(dt))]
dt <- unique(dt, by="comp")

dt[, date:=NULL]
dt[, comp:=NULL]

一个警告:为什么奶酪到奶酪被删除了?我以为你正在寻找不同产品的序列。如果是出于其他原因我的代码可能需要一些调整。

#  client        From          To qty       
#      a      butter      cheese   3 
#      b        milk garbage bag   4 
#      b garbage bag       candy   6
© www.soinside.com 2019 - 2024. All rights reserved.