Accounts Tree erstellt
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
# R/tree_helpers.R
|
||||
|
||||
# Buchungsanzahl rekursiv für einen Knoten und alle Nachkommen
|
||||
count_recursive <- function(num, df, counts) {
|
||||
# Alle Nachkommen: alles im Bereich (num, num+1000) je nach Ebene
|
||||
divisor <- ifelse(num %% 1000 == 0, 1000,
|
||||
ifelse(num %% 100 == 0, 100,
|
||||
ifelse(num %% 10 == 0, 10, 1)))
|
||||
|
||||
descendants <- df$id[
|
||||
df$num >= num &
|
||||
df$num < num + divisor
|
||||
]
|
||||
|
||||
sum(counts$n[counts$account_id %in% descendants], na.rm = TRUE)
|
||||
}
|
||||
|
||||
# Label mit Buchungsanzahl
|
||||
make_label <- function(num, df, counts) {
|
||||
name <- df$account_name[df$num == num]
|
||||
total <- count_recursive(num, df, counts)
|
||||
ifelse(total > 0,
|
||||
paste0(name, " (", total, ")"),
|
||||
name
|
||||
)
|
||||
}
|
||||
|
||||
# Baum rekursiv aufbauen
|
||||
build_level <- function(df, counts, parent_num, divisor) {
|
||||
if (divisor < 1) return(list())
|
||||
|
||||
children <- df[
|
||||
df$num > parent_num &
|
||||
df$num < parent_num + divisor * 10 &
|
||||
df$num %% divisor == 0 &
|
||||
df$num %% (divisor * 10) != 0,
|
||||
]
|
||||
|
||||
if (nrow(children) == 0) return(list())
|
||||
|
||||
result <- lapply(seq_len(nrow(children)), function(i) {
|
||||
child_num <- children$num[i]
|
||||
subtree <- build_level(df, counts, child_num, divisor / 10)
|
||||
if (length(subtree) == 0)
|
||||
structure(list(), sttype = "default")
|
||||
else
|
||||
subtree
|
||||
})
|
||||
|
||||
setNames(result, sapply(children$num, make_label, df = df, counts = counts))
|
||||
}
|
||||
|
||||
# Hauptfunktion: kompletten Baum aus accounts-Tabelle bauen
|
||||
build_account_tree <- function(conn) {
|
||||
df <- dbReadTable(conn, "accounts")
|
||||
df$num <- as.integer(substr(df$account_name, 1, 4))
|
||||
|
||||
counts <- tbl(conn, "postings") %>%
|
||||
count(account_id) %>%
|
||||
collect()
|
||||
|
||||
tops <- df[df$num %% 1000 == 0, ]
|
||||
|
||||
tree <- lapply(seq_len(nrow(tops)), function(i) {
|
||||
build_level(df, counts, tops$num[i], 100)
|
||||
})
|
||||
|
||||
setNames(
|
||||
tree,
|
||||
sapply(tops$num, make_label, df = df, counts = counts)
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user