Creating a user-defined total with grand_summary_rows() - r

I have a table that looks like this:
category family amount
<chr> <chr> <chr>
1 SALES ONLINE SALES 47
2 SALES IN STORE 72
3 COGS LABOR 28
4 COGS TAXES 35
5 COGS WORKERS COMP 24
6 COGS BENEFITS 33
7 EXPENSE AUTOMOBILE 44
8 EXPENSE RENT 12
9 EXPENSE TELEPHONE 26
I am trying to create a gt table from this so I have created this code:
library(tidyverse)
library(gt)
category <- c(rep("SALES",2),
rep("COGS", 4),
rep("EXPENSE",3)
)
family <- c("ONLINE SALES","IN STORE","LABOR","TAXES","WORKERS COMP","BENEFITS",
"AUTOMOBILE", "RENT","TELEPHONE")
amount <- c(47,72,28,35,24,33,44,12,26)
output <- as_tibble(cbind(category,family,amount)) %>%
mutate(amount= as.numeric(amount)) %>%
gt(rowname_col = 'family',
groupname_col = 'category') %>%
row_group_order(c("SALES","COGS", "EXPENSE")) %>%
summary_rows(groups = TRUE,
columns = 'amount',
fns = list(
Total = ~sum(.,na.rm = TRUE)
))
output
How do you get the overall total of SALES-COGS-EXPENSE using the grand_summary_rows() function while all of the amounts are still positive?

if I have correctly understood your request you can use the code below:
output2 <- as_tibble(cbind(category,family,amount)) %>%
mutate(amount= as.numeric(amount)) %>%
gt(rowname_col = 'family', groupname_col = 'category') %>%
summary_rows(groups = TRUE,
columns = 'amount',
fns = list(
Total = ~sum(.,na.rm = TRUE)
)) %>%
grand_summary_rows(
columns = c("family","category","amount"),
fns = list(
"Grand Total" = ~sum(.,na.rm = TRUE)),
formatter = fmt_number,
use_seps = FALSE
)
output2
################### EDIT ###################
The only way I found from the documentation is to create a custom aggregation function. Here's the full working example with the output printscreen.
customFunc <- function(data) {
salesSum <- sum(subset(data$`_data`[,c("amount")], category == 'SALES'))
cogsSum <- sum(subset(data$`_data`[,c("amount")], category == 'COGS'))
expenseSum <- sum(subset(data$`_data`[,c("amount")], category == 'EXPENSE'))
return (salesSum - cogsSum - expenseSum)
}
data <- as_tibble(cbind(category,family,amount)) %>%
mutate(amount= as.numeric(amount)) %>%
gt(rowname_col = 'family', groupname_col = 'category')
output3 <- data %>%
summary_rows(groups = TRUE,
columns = 'amount',
fns = list(
Total = ~sum(.,na.rm = TRUE)
)) %>%
grand_summary_rows(
columns = c("family","category","amount"),
fns = list(
"Grand Total" = ~customFunc(data)),
formatter = fmt_number,
use_seps = FALSE
)
output3

Related

Sparklyr Spark ML Feature Importance after feature transformation

How do i chart or extract feature importance after having gone through feature transformation such as below? Or should i have avoided hot encoding? Due to the transformation (hot encoding), i ended up having more variable importance metrics than the columns themselves.
Thanks
Feature Transformation
fea_pipeline <- ml_pipeline(sc) %>%
ft_string_indexer(input_col = "sex", output_col = "sex_indexed") %>%
ft_string_indexer(input_col = "drinks", output_col = "drinks_indexed") %>%
ft_string_indexer(input_col = "drugs", output_col = "drugs_indexed") %>%
ft_one_hot_encoder(
input_cols = c("sex_indexed", "drinks_indexed", "drugs_indexed"),
output_cols = c("sex_encoded", "drinks_encoded", "drugs_encoded")
) %>%
ft_vector_assembler(
input_cols = c("age", "sex_encoded", "drinks_encoded",
"drugs_encoded", "essay_length"),
output_col = "features"
) %>%
ft_standard_scaler(input_col = "features", output_col = "features_scaled",
with_mean = TRUE) %>%
ml_random_forest_classifier(features_col = "features_scaled",
label_col = "not_working")
Hyper Parameter Tuning
# ------ Hyper Param Tuning ---------
grid <- list(
random_forest = list(
num_trees = c(5, 10),
max_depth = c(10, 20)
)
)
cv <- ml_cross_validator(
sc,
estimator = fea_pipeline,
evaluator = ml_binary_classification_evaluator(sc, label_col = "not_working"),
estimator_param_maps = grid,
num_folds = 5)
cv_model <- ml_fit(cv, train_tbl)
Print the metrics
ml_validation_metrics(cv_model)
fitted <- cv_model$best_model
# ------ Variable Importance ------
ml_tree_feature_importance(ml_stage(fitted,7))
output of variable importance gives me this
0.673134090 0.023902744 0.021771300 0.015035223 0.012361712 0.016907567 0.011370478 0.007484832 0.014057235 0.013598873 0.012238969 0.178136976
I clearly have more importance values than the columns after hot encoding the categorical columns
ml_stage(fea_pipeline,5)$param_map$input_cols
as I have only these columns
[1] "age" "sex_encoded" "drinks_encoded" "drugs_encoded" "essay_length"
Scripts to run to reproduce (pre-Feature Transformation step above)
##Data Download
# download.file(
# "https://github.com/r-spark/okcupid/raw/master/profiles.csv.zip",
# "okcupid.zip")
#
# unzip("okcupid.zip", exdir = "data")
# unlink("okcupid.zip")
#load library
library(sparklyr)
library(ggplot2)
library(dbplot)
library(dplyr)
library(tidyr)
# --------- processining of data---------
sc <- spark_connect(master = "local")
okc <- spark_read_csv(
sc,
"data/profiles.csv",
escape = "\"",
memory = FALSE,
options = list(multiline = TRUE)
) %>%
mutate(height = as.numeric(height),
income = ifelse(income == "-1", NA, as.numeric(income))) %>%
mutate(sex = ifelse(is.na(sex), "missing", sex)) %>%
mutate(drinks = ifelse(is.na(drinks), "missing", drinks)) %>%
mutate(drugs = ifelse(is.na(drugs), "missing", drugs)) %>%
mutate(job = ifelse(is.na(job), "missing", job))
okc <- okc %>%
mutate(
not_working = ifelse(job %in% c("student", "unemployed", "retired"), 1 , 0)
)
ethnicities <- c("asian", "middle eastern", "black", "native american", "indian",
"pacific islander", "hispanic / latin", "white", "other")
ethnicity_vars <- ethnicities %>%
purrr::map(~ expr(ifelse(like(ethnicity, !!.x), 1, 0))) %>%
purrr::set_names(paste0("ethnicity_", gsub("\\s|/", "", ethnicities)))
okc <- mutate(okc, !!!ethnicity_vars)
okc <- okc %>%
mutate(
essay_length = char_length(paste(!!!syms(paste0("essay", 0:9))))
) %>%
select(not_working, age, sex, drinks, drugs, essay1:essay9, essay_length)
# --------- pipeline---------
# Partition the data
partition <-
okc %>%
sdf_random_split(train = 0.7, test = 0.3, seed = 1234)
# Create table references
train_tbl <- partition$train
test_tbl <- partition$test

Missing diacritics in GT table output

I am using GT package in R to create tables for my diploma thesis and I ran into a problem. The diploma is to be written in the czech language.
When GT draws the table it does not display the letter ě properly and shows e instead.
The code for GT table:
desc_sex[,2:ncol(desc_sex)] %>% gt(rowname_col = "sex"
) %>% tab_stubhead(
label = html("Kategorie")
) %>% cols_align(
align = "center",
columns = everything()
) %>% cols_label(
n = html("n"),
procent = html("%")
) %>% tab_row_group(
label = html("<b>Sledované regiony celkem"),
rows = 7:9
) %>% tab_row_group(
label = html("<b>Krajský soud v Ostravě"),
rows = 4:6
) %>% tab_row_group(
label = html("<b>Městský soud v Praze"),
rows = 1:3
) %>% summary_rows(
groups = T,
fns = list(
Celkem = ~sum(.)),
formatter = fmt_number,
decimals = 0
)
Here are the data in CSV compliant format:
"reg_reside","sex","n","procent","single"
"MSPH","Muž",93,46.5,52
"MSPH","Žena",83,41.5,34
"MSPH","Manželský pár",24,12,0
"KSOS","Muž",113,56.5,51
"KSOS","Žena",68,34,30
"KSOS","Manželský pár",19,9.5,0
"Celkem","Muž",206,51.5,103
"Celkem","Žena",151,37.8,64
"Celkem","Manželský pár",43,10.8,0
Here is how the output looks in GT - the mistake is in Ostrave (should be Ostravě) and Mestsky (should be Městský):
You can try using html entities like i.e. ě = &ecaron;
desc_sex[,2:ncol(desc_sex)] %>%
gt(rowname_col = "sex") %>%
tab_stubhead(label = html("Kategorie")) %>%
cols_align(align = "center",columns = everything()) %>%
cols_label(n = html("n"),
procent = html("%")) %>%
tab_row_group(label = html("<b>Sledované regiony celkem"),
rows = 7:9) %>%
tab_row_group(label = html("<b>Krajský soud v Ostrav&ecaron;"),
rows = 4:6) %>%
tab_row_group(label = html("<b>M&ecaron;stský soud v Praze"),
rows = 1:3) %>%
summary_rows(groups = T,
fns = list(Celkem = ~sum(.)),
formatter = fmt_number,
decimals = 0)

Using both hc_motion and hc_drilldown in R Highcharter Map

I am trying to use both hc_motion and hc_drilldown within a highcharter map.
I can manage to get the hc_motion working with the full map, and also a drilldown from a larger area to its smaller ones (UK Region to Local Authority in this instance).
However, after drilling-down and zooming back out again, the hc_motion is now frozen.
Why is this and is there anyway around it? Or are hc_motion and hc_drilldown not compatible?
While in this instance the drilldown is static, if it possible hc_motion within each drilldown would be ideal, although will no even bother trying if even a static can't be incorporated without affecting the hc_motion.
Anyway, example code is below, thanks!
region_lad_lookup = read_csv("https://opendata.arcgis.com/api/v3/datasets/6a41affae7e345a7b2b86602408ea8a2_0/downloads/data?format=csv&spatialRefId=4326") %>%
clean_names() %>%
select(
region_code = rgn21cd,
region_name = rgn21nm,
la_name = lad21nm,
la_code = lad21cd,
value = fid
) %>%
inner_join(
read_sf("https://opendata.arcgis.com/api/v3/datasets/21f7fb2d524b44c8ab9dd0f971c96bba_0/downloads/data?format=geojson&spatialRefId=4326") %>%
clean_names() %>%
filter(grepl("^E", lad21cd)) %>%
select(la_code = lad21cd),
by = "la_code"
)
region_map = read_sf("https://opendata.arcgis.com/api/v3/datasets/bafeb380d7e34f04a3cdf1628752d5c3_0/downloads/data?format=geojson&spatialRefId=4326") %>%
clean_names() %>%
select(
area_code = rgn18cd,
area_name = rgn18nm
) %>%
st_as_sf(crs = 27700) %>%
sf_geojson() %>%
fromJSON(simplifyVector = F)
year_vec = c(2015, 2016, 2017, 2018, 2019)
region_data = region_lad_lookup %>%
select(
area_code = region_code,
area_name = region_name
) %>%
distinct() %>%
crossing(year_vec) %>%
mutate(
value = runif(nrow(.)),
drilldown = tolower(area_name)
)
region_vec = region_data %>%
select(area_name) %>%
distinct() %>%
pull()
get_la_map = function(data, region_val){
data = data %>%
filter(region_name == region_val) %>%
select(
area_code = la_code,
area_name = la_name,
geometry
) %>%
st_as_sf(crs = 27700) %>%
sf_geojson() %>%
fromJSON(simplifyVector = F)
return(data)
}
get_la_data = function(data, region_val){
data = data %>%
filter(region_name == region_val) %>%
select(
area_name = la_name,
area_code = la_code,
value
)
return(data)
}
get_region_map_list = function(region_val){
output = list(
id = tolower(region_val),
data = list_parse(get_la_data(region_lad_lookup, region_val)),
mapData = get_la_map(region_lad_lookup, region_val),
name = region_val,
value = "value",
joinBy = "area_name"
)
return(output)
}
region_ds = region_data %>%
group_by(area_name) %>%
do(
item= list(
area_name = first(.$area_name),
sequence = .$value,
value = first(.$value),
drilldown = first(.$drilldown)
)
) %>%
.$item
highchart(type = "map") %>%
hc_add_series(
data = region_ds,
mapData = region_map,
value = "value",
joinBy = "area_name",
borderWidth = 0
) %>%
hc_colorAxis(
minColor = "lightblue",
maxColor = "red"
) %>%
hc_motion(
enabled = TRUE,
axisLabel = "year",
series = 0,
updateIterval = 200,
magnet = list(
round = "floor",
step = 0.1
)
) %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = lapply(region_vec, get_region_map_list)
)

Create a function using gt package to display tick & cross against approved & non approved customers in R?

I am new in R & have created some Classification models. By using those I need to display tick & cross against approved and rejected customers based Class column.
I picked up a piece of code from somewhere that helps in creating star Ratings against each and it uses gt package
dataframe
df_test <- cbind(prob = predict(model_ranger_py, newdata = test, type = "prob")[,"yes"],
Class = y_test) %>%
rename(Class = y)
df_test
############ output #############
prob Class
<dbl> <fctr>
3 0.4906592 no
6 0.6123333 no
12 0.3746750 no
14 0.4906592 no
22 0.7820000 yes
24 0.5333956 no
29 0.5281762 no
45 0.7413333 no
46 0.7413333 no
50 0.5333956 no
53 0.5333956 no
54 0.7560000 yes
57 0.4906592 no
59 0.5281762 no
62 0.7413333 no
64 0.6626619 no
68 0.4906592 no
74 0.7413333 no
75 0.5333956 yes
76 0.5333956 no
Reference code to create star ratings by using gt & fontawesome packages (this works)
library(tidyverse)
library(gt)
library(htmltools)
library(fontawesome)
Creating function
rating_stars5 <- function(rating, max_rating = 5){
rounded_rating <- floor(rating + 0.5)
stars <- lapply(seq_len(max_rating), function(i){
if(i <= rounded_rating){
fontawesome::fa("star", fill = "orange")
} else{
fontawesome::fa("star", fill = "grey")
}
})
label <- sprintf("%s out of %s", rating, max_rating)
# label <- glue("{rating} out of {max_rating}")
div_out <- div(title = label, "aria-label" = label, role = "img", stars)
as.character(div_out) %>%
gt::html()
}
Applying function on dataframe
df_test %>%
# creating customerid based on row index
mutate(customerid = row.names(.)) %>%
# converting to 5 bins to match 5 stars
mutate(rating = cut_number(prob, n =5) %>% as.numeric()) %>%
mutate(rating = map(rating, rating_stars5)) %>%
arrange(customerid) %>%
# to limit the number of rows in rmarkdown rendered doc
head(n = 15) %>%
gt() %>%
tab_header(title = gt::md("__BankMarketing Term Plan Customer Response Likelyhood__")) %>%
tab_spanner(
label = gt::html("<small>High Stars = higher chances</small>"),
columns = vars(customerid, prob, Class)
) %>%
# table styling to reduce text size
tab_style(
style = cell_text(size = px(12)),
locations = cells_body(
columns = vars(customerid, prob, Class)
)
) %>%
cols_label(
customerid = gt::md("__CUSTOMER__")
)
This creates a nice html table:
Issue:
In above html table instead of Star Ratings I am trying to get tick/cross based on yes/no from class column but unable to do it. This is what I have tried:
# 1. creating function
rating_yes_no <- function(Class){
check_cross <- lapply(Class, function(i){
if(i == "yes"){
fontawesome::fa("check", fill = "green")
} else{
fontawesome::fa("times", fill = "red")
}
})
label <- sprintf("%s", check_cross)
# label <- glue("{check_cross} ")
div_out <- div(title = label, "aria-label" = label, role = "img", check_cross)
as.character(div_out) %>%
gt::html()
}
# 2. Applying function
df_test %>%
mutate(customerid = row.names(.)) %>%
mutate(class_rating = map(class_rating, rating_yes_no)) %>%
arrange(customerid) %>%
# to limit the number of rows in rmarkdown rendered doc
head(n = 15) %>%
gt() %>%
tab_header(title = gt::md("__BankMarketing Term Plan Customer Response Likelyhood__")) %>%
tab_spanner(
label = gt::html("<small>High Stars = higher chances</small>"),
columns = vars(customerid, prob, Class)
) %>%
# table styling to reduce text size
tab_style(
style = cell_text(size = px(12)),
locations = cells_body(
columns = vars(customerid, prob, Class)
)
) %>%
cols_label(
customerid = gt::md("__CUSTOMER__")
)
Had some silly mistakes, below code worked:
rating_yes_no <- function(Class){
check_cross <- lapply(Class, function(i){
if(i == "yes"){
fontawesome::fa("check", fill = "green")
} else{
fontawesome::fa("times", fill = "red")
}
})
label <- sprintf("%s", Class)
# label <- glue("{rating} out of {max_rating}")
div_out <- div(title = label, "aria-label" = label, role = "img", check_cross)
as.character(div_out) %>%
gt::html()
}
df_test %>%
mutate(customerid = row.names(.)) %>%
mutate(class_rating = map(Class, rating_yes_no)) %>%
arrange(customerid) %>%
# to limit the number of rows in rmarkdown rendered doc
head(n = 15) %>%
gt() %>%
tab_header(title = gt::md("__BankMarketing Term Plan Customer Response Likelyhood__")) %>%
tab_spanner(
label = gt::html("<small>High Stars = higher chances</small>"),
columns = vars(customerid, prob, Class)
) %>%
# table styling to reduce text size
tab_style(
style = cell_text(size = px(12)),
locations = cells_body(
columns = vars(customerid, prob, Class)
)
) %>%
cols_label(
customerid = gt::md("__CUSTOMER__")
)

R - Highcharter: Drilldown on stacked column graph

I've created a stacked column chart in Highcharter using R and I am trying to be able to drilldown into it.
I.e. In the picture attached, I want to be able to drill down in the red section of column CRDT. So far, I can only get it so each color section of CRDT drills into the same information OR each red section drills into the same information. I need a combined filter.
Below is my code that drills "CRDT Red" information for all red sections:
Lvl1Grouping <- aggregate(WIPGate2$Receipt.Qty, by = list(WIPGate$Hold.Code,WIPGate2$Aging),FUN=sum)
Lvl1df <- data_frame(name = Lvl1Grouping$Group.1,
y = Lvl1Grouping$x,
stack = Lvl1Grouping$Group.2,
drilldown = tolower(stack)
)
hc <- highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = "WIP") %>%
hc_xAxis(type = "category") %>%
hc_legend(enabled = FALSE) %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_add_series(name = "Greater than 30 days",data=Lvl1dfLvl1df$stack=="Greater than 30 days",], color = "#D20000") %>%
hc_add_series(name = "Between 20-30 days",data=Lvl1df[Lvl1df$stack=="Between 20-30 days",], color = "#FF7900") %>%
hc_add_series(name = "Between 10-20 days",data=Lvl1df[Lvl1df$stack=="Between 10-20 days",], color = "#F6FC00") %>%
hc_add_series(name = "Less than 10 days",data=Lvl1df[Lvl1df$stack=="Less than 10 days",], color = "#009A00")
hc
Lvl2GroupingCRDT <- WIPGate2[WIPGate2$Hold.Code == "CRDT",]
Lvl2GroupingCRDT4 <- Lvl2GroupingCRDT[Lvl2GroupingCRDT$Aging == "Greater than 30 days",]
Lvl2GroupingCRDT4 <- aggregate(Lvl2GroupingCRDT4$Receipt.Qty, by = list(Lvl2GroupingCRDT4$Customer.Name),FUN=sum)
dfCRDT4 <- data_frame(
name = Lvl2GroupingCRDT4$Group.1,
value = Lvl2GroupingCRDT4$x
)
hc <- hc %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = list(
list(
id = "greater than 30 days",
name = "CRDT",
data = list_parse2(dfCRDT4)
)
)
)
hc
Current Situation .png
I have figured out the code, however it is not an eloquent solution...
The trick is instead of having a single data frame for the Level 1 information, there needs to be a separate data frame for each part of the stack. This way you can put an ID to it in order to be able to reference.
My code is hundreds of lines in order to splice out the data in the way it needs to be so if anyone has a better solution, please post it!! (my actually code includes 7 other groups besides "CRDT", so imagine "CRDT" lines below * 7!!!
FYI, I have changed some of my dashboard and variables, so they may not be the same as above...
WIPGate2Aging <- WIP_Ops_Filtered()[WIP_Ops_Filtered()$Hold.Code!="",]
WIPGate2G30 <- WIPGate2Aging[WIPGate2Aging$Aging == "Greater than 30 days",]
WIPGate22030 <- WIPGate2Aging[WIPGate2Aging$Aging == "Between 20-30 days",]
WIPGate21020 <- WIPGate2Aging[WIPGate2Aging$Aging == "Between 10-20 days",]
WIPGate2L10 <- WIPGate2Aging[WIPGate2Aging$Aging == "Less than 10 days",]
try(Lvl1GroupingG30 <- aggregate(WIPGate2G30$Receipt.Qty, by = list(WIPGate2G30$Hold.Code),FUN=sum),silent = TRUE)
if (exists("Lvl1GroupingG30")) {} else {Lvl1GroupingG30=data.table(Group.1=numeric(), x=numeric())}
try(Lvl1Grouping2030 <- aggregate(WIPGate22030$Receipt.Qty, by = list(WIPGate22030$Hold.Code),FUN=sum),silent = TRUE)
if (exists("Lvl1Grouping2030")) {} else {Lvl1Grouping2030=data.table(Group.1=numeric(), x=numeric())}
try(Lvl1Grouping1020 <- aggregate(WIPGate21020$Receipt.Qty, by = list(WIPGate21020$Hold.Code),FUN=sum),silent = TRUE)
if (exists("Lvl1Grouping1020")) {} else {Lvl1Grouping1020=data.table(Group.1=numeric(), x=numeric())}
try(Lvl1GroupingL10 <- aggregate(WIPGate2L10$Receipt.Qty, by = list(WIPGate2L10$Hold.Code),FUN=sum),silent = TRUE)
if (exists("Lvl1GroupingL10")) {} else {Lvl1GroupingL10=data.table(Group.1=numeric(), x=numeric())}
Lvl1dfG30 <- data_frame(name = Lvl1GroupingG30$Group.1, y = Lvl1GroupingG30$x, drilldown = tolower((paste(name,"4"))))
Lvl1df2030 <- data_frame(name = Lvl1Grouping2030$Group.1, y = Lvl1Grouping2030$x, drilldown = tolower((paste(name,"3"))))
Lvl1df1020 <- data_frame(name = Lvl1Grouping1020$Group.1, y = Lvl1Grouping1020$x, drilldown = tolower((paste(name,"2"))))
Lvl1dfL10 <- data_frame(name = Lvl1GroupingL10$Group.1, y = Lvl1GroupingL10$x, drilldown = tolower((paste(name,"1"))))
Lvl2GroupingCRDTG30 <- WIPGate2Aging[WIPGate2Aging$Hold.Code == "CRDT" & WIPGate2Aging$Aging == "Greater than 30 days",]
try(Lvl2GroupingCRDTG30b <- aggregate(Lvl2GroupingCRDTG30$Receipt.Qty, by = list(Lvl2GroupingCRDTG30$Customer.Name),FUN=sum),silent = TRUE)
if (exists("Lvl2GroupingCRDTG30b")) {} else {Lvl2GroupingCRDTG30b=data.table(Group.1=numeric(), x=numeric())}
Lvl2GroupingCRDT2030 <- WIPGate2Aging[WIPGate2Aging$Hold.Code == "CRDT" & WIPGate2Aging$Aging == "Between 20-30 days",]
try(Lvl2GroupingCRDT2030b <- aggregate(Lvl2GroupingCRDT2030$Receipt.Qty, by = list(Lvl2GroupingCRDT2030$Customer.Name),FUN=sum),silent = TRUE)
if (exists("Lvl2GroupingCRDT2030b")) {} else {Lvl2GroupingCRDT2030b=data.table(Group.1=numeric(), x=numeric())}
Lvl2GroupingCRDT1020 <- WIPGate2Aging[WIPGate2Aging$Hold.Code == "CRDT" & WIPGate2Aging$Aging == "Between 10-20 days",]
try(Lvl2GroupingCRDT1020b <- aggregate(Lvl2GroupingCRDT1020$Receipt.Qty, by = list(Lvl2GroupingCRDT1020$Customer.Name),FUN=sum),silent = TRUE)
if (exists("Lvl2GroupingCRDT1020b")) {} else {Lvl2GroupingCRDT1020b=data.table(Group.1=numeric(), x=numeric())}
Lvl2GroupingCRDTL10 <- WIPGate2Aging[WIPGate2Aging$Hold.Code == "CRDT" & WIPGate2Aging$Aging == "Less than 10 days",]
try(Lvl2GroupingCRDTL10b <- aggregate(Lvl2GroupingCRDTL10$Receipt.Qty, by = list(Lvl2GroupingCRDTL10$Customer.Name),FUN=sum),silent = TRUE)
if (exists("Lvl2GroupingCRDTL10b")) {} else {Lvl2GroupingCRDTL10b=data.table(Group.1=numeric(), x=numeric())}
dfCRDTG30 <- arrange(data_frame(name = Lvl2GroupingCRDTG30b$Group.1,value = Lvl2GroupingCRDTG30b$x),desc(value))
dfCRDT2030 <- arrange(data_frame(name = Lvl2GroupingCRDT2030b$Group.1,value = Lvl2GroupingCRDT2030b$x),desc(value))
dfCRDT1020 <- arrange(data_frame(name = Lvl2GroupingCRDT1020b$Group.1,value = Lvl2GroupingCRDT1020b$x),desc(value))
dfCRDTL10 <- arrange(data_frame(name = Lvl2GroupingCRDTL10b$Group.1,value = Lvl2GroupingCRDTL10b$x),desc(value))
highchart() %>%
hc_chart(type = "column") %>%
hc_xAxis(type = "category") %>%
hc_yAxis(gridLineWidth = 0) %>%
hc_legend(enabled = TRUE) %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_add_series(name = "Greater than 30 days",data=Lvl1dfG30, color = "#D20000") %>%
hc_add_series(name = "Between 20-30 days",data=Lvl1df2030, color = "#FF7900") %>%
hc_add_series(name = "Between 10-20 days",data=Lvl1df1020, color = "#F6FC00") %>%
hc_add_series(name = "Less than 10 days",data=Lvl1dfL10, color = "#009A00") %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = list(
list(id = "crdt 4", data = list_parse2(dfCRDTG30), name="Customer"),
list(id = "crdt 3", data = list_parse2(dfCRDT2030), name="Customer"),
list(id = "crdt 2", data = list_parse2(dfCRDT1020), name="Customer"),
list(id = "crdt 1", data = list_parse2(dfCRDTL10), name="Customer")))

Resources