View source: R/generate_code.R
generate_aggregation_code | R Documentation |
Reads metadata from a master data.table and generates executable data.table code strings for performing aggregations.
generate_aggregation_code(table_name_filter, metadata_dt)
table_name_filter |
Character string, the name of the table for which to generate aggregation code. |
metadata_dt |
A data.table containing the master metadata, created by
calling |
A named character vector where each element is a runnable
data.table
code string, and the names correspond to the grouping variables.
# First, create some metadata
customers_info <- table_info(
table_name = "customers",
source_identifier = "customers.csv",
identifier_columns = "customer_id",
key_outcome_specs = list(
list(OutcomeName = "CustomerCount", ValueExpression = 1, AggregationMethods = list(
list(AggregatedName = "CountByRegion", AggregationFunction = "sum",
GroupingVariables = "region")
))
))
transactions_info <- table_info(
table_name = "transactions",
source_identifier = "transactions.csv",
identifier_columns = "transaction_id",
key_outcome_specs = list(
list(OutcomeName = "Revenue", ValueExpression = quote(amount), AggregationMethods = list(
list(AggregatedName = "RevenueByCustomer", AggregationFunction = "sum",
GroupingVariables = "customer_id"),
list(AggregatedName = "RevenueByProduct", AggregationFunction = "sum",
GroupingVariables = "product_id")
)),
list(OutcomeName = "Transactions", ValueExpression = 1, AggregationMethods = list(
list(AggregatedName = "TransactionsByCustomer", AggregationFunction = "sum",
GroupingVariables = "customer_id")
))
))
master_metadata <- data.table::rbindlist(list(customers_info, transactions_info))
# Now, generate the code for the "transactions" table
generated_code <- generate_aggregation_code("transactions", master_metadata)
print(generated_code)
# To demonstrate execution:
# 1. Create the sample data
transactions <- data.table::data.table(
transaction_id = c("T001", "T002", "T003"),
customer_id = c("C001", "C002", "C001"),
product_id = c("P001", "P002", "P001"),
amount = c(10.0, 20.0, 15.0)
)
# 2. Parse and evaluate the first generated statement
revenue_by_customer_code <- generated_code["customer_id"]
cat("Executing code:\n", revenue_by_customer_code)
revenue_by_customer_dt <- eval(parse(text = revenue_by_customer_code))
print(revenue_by_customer_dt)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.