Skip to content

Commit

Permalink
better management of duplicate labels
Browse files Browse the repository at this point in the history
  • Loading branch information
GuyliannEngels committed Jun 6, 2024
1 parent 04e3452 commit c59fc05
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion R/equation.R
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ print.inline_equation <- function(x, ...) {
labels[i] <- gsub("(.*)(\\n \\[)(.*)(\\])",
paste0("\\1", vec, "\\2", "\\3", vec,"\\4"), labels[i])
} else {
labels[i] <- paste0(labels[i], sous_chaine)
labels[i] <- paste0(labels[i], vec)
}
}
}
Expand Down
1 change: 1 addition & 0 deletions R/tabularise_default.R
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ tabularise_default.data.frame <- function(data, formula = NULL,
# Use a \n before the units
labels <- sub(" +\\[([^]]+)\\]$", "\n[\\1]", labels)
labels[labels == ""] <- names(data)[labels == ""] # set names if empty
labels <- .handle_duplicate_labels(labels,replace_with_name = TRUE)
names(data) <- as.character(labels)
# Also rework col_keys accordingly
keys <- as.character(labels[col_keys])
Expand Down
36 changes: 36 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,39 @@ args_type <- function(fun, method = NULL, type) {
# 3. Do the same but select "fun", now you got the arguments for the fun type
# 4. Just write a new `.head2_<type>` function and <type> is automatically
# integrated!

# This function handles duplicates in a vector of labels. It either replaces
# duplicates with their names or adds a number to the end of each duplicate
# element. If replace_with_name is TRUE (default), duplicates are replaced with
# their names.

.handle_duplicate_labels <- function(x, replace_with_name = TRUE) {
# Check for duplicates
#duplicates <- collapse::fduplicated(x)
duplicates <- duplicated(x) | duplicated(x, fromLast = TRUE)

if(any(duplicates)) {
warning(
"Warning: There are duplicate elements in the labels.
Tip: Use data.io::labelise() to replace your duplicate labels.")

if(replace_with_name) {
# Replace duplicates with their names
x[duplicates] <- names(x)[duplicates]
} else {
# Count occurrences of each element
counts <- table(x)

# Find duplicate elements
duplicates <- names(counts[counts > 1])

# For each duplicate element, add a number at the end
for (name in duplicates) {
index <- which(x == name)
x[index] <- paste(x[index], "(", seq_along(index), ")", sep = "")
}
}
}

return(x)
}

0 comments on commit c59fc05

Please sign in to comment.