The Turf R6 class performs Total Unduplicated Reach and
Frequency (TURF) analysis.
It handles:
TURF Data preparation.
Calculation of reach metrics, including:
Threshold-based reach
Popular-top-N reach
Utility-weighted reach
Plotting of results via a dedicated
$plotaccessor, which provides methods like:incremental_plot(): visualizes reach across combination sizes.topN_plot(): plots top-N combinations for a given size.
Public fields
matricesA list containing the raw input matrices
attributesItem attributes
weightsA dataframe containing the weights.
combinationsThe generated combinations, stored as a tibble or as a list of Job objects if offloaded.
use_kubernetesLogical; if TRUE, heavy operations will be offloaded to Kubernetes.
heavy_thresholdNumeric threshold for considering an operation "heavy". Default is 1e5.
turf_outputList of TURF results.
plotPlot accessor. See
TurfPlotter()for more documentation.
Methods
Method new()
Create a new TURF object.
Usage
Turf$new(
data,
id = "response_id",
attribute = "attribute",
utilities = "utility",
probability = "probability",
weights = NULL,
heavy_threshold = 5e+06
)Arguments
dataA dataframe containing the input data.
idCharacter string for the respondent identifier column. Default is "response_id".
attributeCharacter string for the attributes column. Default is "attribute".
utilitiesA character string specifying the column name for the utility values.
probabilityA character string specifying the column name for the probability values.
weightsA character string specifying the column name for weights. By default (NULL) it sets weights as 1.
heavy_thresholdNumeric threshold for heavy operations. Default is 1e5.
Method generate_combinations()
Generate Combinations
For each combination size provided, if the number of
possible combinations exceeds heavy_threshold, a
check is performed (once) to decide how to handle heavy
operations. The user is prompted to choose whether to
offload heavy operations to Kubernetes. That decision
is saved in use_kubernetes and applied to all
subsequent heavy operations.
Method calc_threshold_reach()
Calculate Threshold Reach
Calculates threshold reach metrics for each generated combination.
Method calc_threshold_reach_popular()
Calculate Threshold-Based “Popular” Reach
For each combination length, binarize the internal probability matrix at the given threshold, then convert to turf reach data and compute “popular reach”—i.e. the proportion of respondents who are reached by at least one of the most widely selected (most “popular”) items in that combination.
Arguments
thresholdNumeric scalar. Probability cutoff to decide which responses are “active”. If NULL, it automatically infers it.
n_popularInteger scalar or integer vector. If NULL, defaults to each combination’s length. When a single positive integer is provided, it applies uniformly to all combinations; when a vector, it must be a positive integer vector of length equal to the number of combinations.
...Not used yet. Additional arguments passed to the Kubernetes job (if applicable).
Method calc_weighted_reach()
Calculate Weighted Reach
Method refresh_kubernetes_metrics()
Refresh Kubernetes Metrics
Attempts to collect the results of Kubernetes jobs
stored in metrics for a given metric id. If not all
results are ready, the user is alerted and the current
list is retained.
Method turf_apply_metric_to_combinations()
Apply a Metric Function to Turf Combinations
This function applies a user-specified metric function
to each combination in the combination column of a
data frame, and stores the results in the metrics
list-column under the specified column name.
Arguments
turf_datalist or list of lists of turf_data.
combination_dfA data frame that contains:
a
combinationcolumn where each element is typically a matrix,a
metricslist-column for storing metric results.
FUNA function to be applied to each column of the combination matrix. This function should accept at least an argument
portfoliorepresenting one combination.colnameA character string specifying the name of the metric column to be added (or overwritten) in
combination_df$metrics....Additional arguments to be passed to FUN.
Method prepare_export_output()
Prepare Export Output
Constructs a list of tidy tibbles representing each combination and its
associated metrics in a format ready for export. This includes styling
for Excel-friendly formatting (e.g., number formats and cell fills). The
output is saved to the internal field self$turf_output.
Method export()
Export combinations and metrics.
Exports the current set of attribute‐combinations along with all calculated metrics.
Examples
library(openxlsx)
library(stringr)
library(dplyr)
#>
#> Attaching package: ‘dplyr’
#> The following objects are masked from ‘package:stats’:
#>
#> filter, lag
#> The following objects are masked from ‘package:base’:
#>
#> intersect, setdiff, setequal, union
## Initializes turf object
turf <- Turf$new(
example_md_turf_data,
id = "id",
attribute = "item",
utilities = "pwu",
probability = "probability",
weights = NULL,
heavy_threshold = 1e5
)
turf
#>
#> ── [Turf] Total Unduplicated Reach & Frequency ─────────────────────────────────
#> • Respondents: 213
#> • Attributes: 6
#> • Combinations: 0
#> • Metrics: 0
#> ────────────────────────────────────────────────────────────────────────────────
## Check data
turf$attributes
#> [1] Affirmative action gives an unfair advantage to certain people based o
#> [2] America’s current political system is responsive to the will of the
#> [3] It is essential for a healthy democracy that Americans engage with oth
#> [4] The electoral college should be abolished so that every American’s v
#> [5] The federal government should regulate user-generated content on socia
#> [6] The government should impose fines on speech that is perceived as offe
#> 6 Levels: Affirmative action gives an unfair advantage to certain people based o ...
turf$matrices$utilities |> head()
#> 1 2 3 4 5
#> R_0BySpORZ9EPy9mp -0.1896848 -1.413736 -0.024131889 -1.97428111 -2.150869
#> R_10TQxH1gIYXisxR -3.9371784 -4.291036 -0.793114415 -1.73895122 -6.119241
#> R_129fm9Ak9Gct3hF -6.9753503 -8.030469 -1.597885474 -0.12232920 -8.284272
#> R_12FJZrjUPFfhOzi 0.2458459 -2.958410 -1.811109442 -0.08580885 -1.636671
#> R_12rmz2fdiNXiGqm -5.1230035 -4.261671 -1.487502116 0.30934658 -4.361128
#> R_1BQ96mlpvzJakZ7 1.6092724 -3.112769 -0.007603553 -2.08928008 -2.780495
#> 6
#> R_0BySpORZ9EPy9mp -1.959537
#> R_10TQxH1gIYXisxR -6.107658
#> R_129fm9Ak9Gct3hF -7.443167
#> R_12FJZrjUPFfhOzi -1.306116
#> R_12rmz2fdiNXiGqm -5.348011
#> R_1BQ96mlpvzJakZ7 -3.991859
turf$matrices$probabilities |> head()
#> 1 2 3 4 5
#> R_0BySpORZ9EPy9mp 0.3386390869 0.0995722412 0.39960949 0.05684559 0.0476436953
#> R_10TQxH1gIYXisxR 0.0292946856 0.0205641293 0.67957667 0.26391663 0.0033046928
#> R_129fm9Ak9Gct3hF 0.0008580346 0.0002987257 0.18574113 0.81233290 0.0002317647
#> R_12FJZrjUPFfhOzi 0.4444039127 0.0180379476 0.05681376 0.31896426 0.0676411527
#> R_12rmz2fdiNXiGqm 0.0036641579 0.0086705363 0.13894802 0.83794174 0.0078496867
#> R_1BQ96mlpvzJakZ7 0.8011077517 0.0071274540 0.15903423 0.01983490 0.0099366278
#> 6
#> R_0BySpORZ9EPy9mp 0.0576899049
#> R_10TQxH1gIYXisxR 0.0033431943
#> R_129fm9Ak9Gct3hF 0.0005374455
#> R_12FJZrjUPFfhOzi 0.0941389674
#> R_12rmz2fdiNXiGqm 0.0029258683
#> R_1BQ96mlpvzJakZ7 0.0029590372
turf$weights |> head()
#> # A tibble: 6 × 2
#> id weight
#> <chr> <dbl>
#> 1 R_0BySpORZ9EPy9mp 1
#> 2 R_10TQxH1gIYXisxR 1
#> 3 R_129fm9Ak9Gct3hF 1
#> 4 R_12FJZrjUPFfhOzi 1
#> 5 R_12rmz2fdiNXiGqm 1
#> 6 R_1BQ96mlpvzJakZ7 1
## Generate combinations
turf$generate_combinations()
turf$combinations
#> # A tibble: 6 × 3
#> combination_length combination metrics
#> <int> <list> <tibble[,0]>
#> 1 1 <int [1 × 6]>
#> 2 2 <int [2 × 15]>
#> 3 3 <int [3 × 20]>
#> 4 4 <int [4 × 15]>
#> 5 5 <int [5 × 6]>
#> 6 6 <int [6 × 1]>
## Calculate reach
turf$calc_threshold_reach(threshold = 0.08)
#> ℹ Processed 213 respondents into 41 unique patterns.
# Default: use each combination’s length as the number of “popular” items
# (e.g., a 3-item combination → top 3 items; a 1-item combination → top 1 item),
# then compute reach at probability ≥ 0.08 for those items.
turf$calc_threshold_reach_popular(threshold = 0.08)
#> ℹ Processed 213 respondents into 6 unique patterns.
#> ℹ Processed 213 respondents into 17 unique patterns.
#> ℹ Processed 213 respondents into 29 unique patterns.
#> ℹ Processed 213 respondents into 36 unique patterns.
#> ℹ Processed 213 respondents into 40 unique patterns.
#> ℹ Processed 213 respondents into 41 unique patterns.
# Uniform popular count: always take the top 1 item, regardless of combination length,
# then compute reach at probability ≥ 0.08 for that item.
turf$calc_threshold_reach_popular(threshold = 0.08, n_popular = 1L)
#> ℹ Processed 213 respondents into 6 unique patterns.
#> ℹ Processed 213 respondents into 6 unique patterns.
#> ℹ Processed 213 respondents into 6 unique patterns.
#> ℹ Processed 213 respondents into 6 unique patterns.
#> ℹ Processed 213 respondents into 6 unique patterns.
#> ℹ Processed 213 respondents into 6 unique patterns.
#> ! Metric column 'threshold_reach_popular_0.08' already exists and will be overwritten.
# Custom popular counts: supply a distinct number of top items for each combination.
# Length of `n_popular` must match the number of combinations.
turf$calc_threshold_reach_popular(threshold = 0.08, n_popular = c(2L, 3L, 4L, 1L, 2L, 5L))
#> ℹ Processed 213 respondents into 17 unique patterns.
#> ℹ Processed 213 respondents into 29 unique patterns.
#> ℹ Processed 213 respondents into 36 unique patterns.
#> ℹ Processed 213 respondents into 6 unique patterns.
#> ℹ Processed 213 respondents into 17 unique patterns.
#> ℹ Processed 213 respondents into 40 unique patterns.
#> ! Metric column 'threshold_reach_popular_0.08' already exists and will be overwritten.
turf$calc_weighted_reach(a = 5L)
turf$combinations
#> # A tibble: 6 × 3
#> combination_length combination metrics$threshold_reach_0.08
#> <int> <list> <list>
#> 1 1 <int [1 × 6]> <tibble [6 × 2]>
#> 2 2 <int [2 × 15]> <tibble [15 × 2]>
#> 3 3 <int [3 × 20]> <tibble [20 × 2]>
#> 4 4 <int [4 × 15]> <tibble [15 × 2]>
#> 5 5 <int [5 × 6]> <tibble [6 × 2]>
#> 6 6 <int [6 × 1]> <tibble [1 × 2]>
#> # ℹ 2 more variables: metrics$threshold_reach_popular_0.08 <list>,
#> # $weighted_reach <list>
## Show available metrics
turf$show_metrics()
#> [1] "threshold_reach_0.08" "threshold_reach_popular_0.08"
#> [3] "weighted_reach"
# Export results
wb <- turf$export()
out_dir <- file.path(tempdir(), "g6tr.md")
if (!dir.exists(out_dir)) dir.create(out_dir, recursive = TRUE)
openxlsx::saveWorkbook(
wb,
file.path(out_dir, "example_wb_metrics.xlsx")
)
## Plotting
## Incremental Reach
turf$plot$incremental_plot(metric = "threshold_reach_popular_0.08")
#> copying font files to ~/.local/share/fonts : AnekLatin
#> copying font files to ~/.local/share/fonts : IBMPlexMono
#> copying font files to ~/.local/share/fonts : IBMPlexSans
#> copying font files to ~/.local/share/fonts : Lato
#> copying font files to ~/.local/share/fonts : OpenSans
#> copying font files to ~/.local/share/fonts : Raleway
#>
#> [!] You may need to restart the session (Ctrl + Shift + F10) to make the fonts work.
## When a combination size is selected, you can decide to plot the topN
## items in that combination size.
## For customization, there are three ways to set color palette
## 1. NULL
turf$plot$topN_plot(metric = "threshold_reach_popular_0.08", n_item = 4)
## 2. A named vector of colors
col_pal_vec <- c("#36c8ef",
"#50bd90",
"#de425b",
"#ffcf60",
"#EF8150",
"#3693EF")
names(col_pal_vec) <- turf$attributes
turf$plot$topN_plot(metric = "threshold_reach_popular_0.08",
n_item = 4,
color_palette = col_pal_vec)
## 3. A data frame with attribute and y_label columns
## This is mostly used if there's some custom styling needed
col_pal_df <-
tibble(attribute = turf$attributes) |>
mutate(
color = case_when(
str_detect(attribute, "^A") ~ "#de425b",
str_detect(attribute, "^I") ~ "#50bd90",
str_detect(attribute, "^T") ~ "#3693EF"
),
y_label = case_when(
str_detect(attribute, "^A") ~ paste0("Group A: ", attribute),
str_detect(attribute, "^I") ~ paste0("Group B: ", attribute),
str_detect(attribute, "^T") ~ paste0("Group C: ", attribute)
)
) |>
mutate(y_label = wrap_and_color(y_label, color, 60)) |>
select(-"color")
## wrap_and_color() is a helper function that wraps text and applies color
## in the format to be used in {ggtext}.
turf$plot$topN_plot(metric = "threshold_reach_popular_0.08",
n_item = 4,
color_palette = col_pal_df)