- allow_reverse: logical, whether to allow ranges like "10-7" and reverse them
if (is.na(input_string) || str_trim(input_string) == "") {
return(numeric())
}
parts <- str_split(input_string, ",")[[1]]
parts <- str_trim(parts)
result <- numeric()
for (part in parts) {
if (str_detect(part, "-")) {
range_parts <- str_split(part, "-")[[1]]
if (length(range_parts) != 2) {
if (warn) warning(paste("Invalid range format (too many hyphens):", part, ". Skipping."))
next
}
start <- as.integer(range_parts[1])
end <- as.integer(range_parts[2])
if (is.na(start) || is.na(end)) {
if (warn) warning(paste("Non-integer range values:", part, ". Skipping."))
next
}
if (start > end && allow_reverse) {
tmp <- start
start <- end
end <- tmp
}
if (start <= end) {
# Apply bounds
bounded_start <- max(start, min_val)
bounded_end <- min(end, max_val)
if (bounded_start <= bounded_end) {
result <- c(result, bounded_start:bounded_end)
} else {
if (warn) warning(paste("Range outside bounds after adjustment:", part, ". Skipping."))
}
} else {
if (warn) warning(paste("Invalid range (start > end):", part, ". Skipping."))
}
} else {
# Single integer
num <- suppressWarnings(as.integer(part))
if (!is.na(num)) {
bounded_num <- max(min_val, min(num, max_val))
result <- c(result, bounded_num)
} else {
if (warn) warning(paste("Invalid integer:", part, ". Skipping."))
}
}
}
return(sort(unique(result)))
}
Assistant
This function is well-structured, robust, and clearly documented — it does a great job of parsing a string that represents a list of integers or integer ranges (e.g., "1-5,8,10-12") and returns a sorted vector of unique integers within the specified bounds.
Here’s a detailed breakdown of what’s good, and some suggestions for improvement or optimization:
✅ What’s Good About the Function
1. Comprehensive Input Handling
It gracefully handles NA or empty strings by returning an empty numeric vector.
It trims whitespace around parts (e.g., " 5-7 , 9 ") to ensure flexibility in input formatting.
2. Robust Parsing Logic
Splits the input by commas and processes each part individually.
Distinguishes between single integers and ranges.
Handles invalid or malformed input with appropriate warnings and skips them.
3. Flexible Range Handling
Supports reversed ranges (e.g., "10-7") if allow_reverse = TRUE.
Clamps values to min_val and max_val to avoid out-of-bounds values.
4. Warnings and Error Handling
Uses informative warnings for malformed input, helping users debug their input strings.
Avoids errors by checking for NA after conversions.
5. Final Output Sanitization
Returns a sorted, unique vector of integers, which is clean and easy to use.
🛠️ Suggestions for Improvement
1. Use of str_split and str_trim from stringr
This is fine if you're already using stringr, but if you want to reduce dependencies, you could use base R equivalents:
parts <- trimws(strsplit(input_string, ",")[[1]])
2. Avoid Growing Objects in a Loop
Appending to result with c(result, ...) in a loop can be inefficient for large inputs.
Consider preallocating a list and unlisting at the end:
User
ok, what would be your perfect 10/10 function? (Note: I don't want support for negative numbers or floating points!)
Assistant
Great! Since you're happy with the current logic and don’t want support for negative numbers or floating points, we can refine your original function into a clean, efficient, and robust 10/10 version with the following goals:
🎯 Goals for the 10/10 Function
Maintain current behavior: parsing comma-separated ranges and integers, clamping to bounds, sorting and deduplication.
Avoid external dependencies (i.e., drop stringr).
Improve performance by avoiding vector growth in loops.
Add basic input validation.
Make it readable and maintainable.
✅ Final Version: parse_integer_range_or_list
parse_integer_range_or_list <- function(input_string, min_val = 1, max_val = 1000,
warn = TRUE, allow_reverse = FALSE) {
# Parses a comma-separated string of integers and ranges.
# Returns a sorted vector of unique integers within [min_val, max_val].
# Does not support negative numbers or floating points.
if (min_val > max_val) stop("'min_val' must be <= 'max_val'")
input_string <- trimws(input_string)
if (is.na(input_string) || input_string == "") return(numeric())
parts <- strsplit(input_string, ",")[[1]]
parts <- trimws(parts)
result <- list() # Use a list to collect ranges efficiently
for (part in parts) {
if (grepl("-", part)) {
range_parts <- strsplit(part, "-")[[1]]
if (length(range_parts) != 2) {
if (warn) warning("Invalid range format (too many hyphens): ", part, ". Skipping.")
next
}
start <- suppressWarnings(as.integer(range_parts[1]))
end <- suppressWarnings(as.integer(range_parts[2]))
if (is.na(start) || is.na(end)) {
if (warn) warning("Non-integer range values: ", part, ". Skipping.")
next
}
if (start > end && allow_reverse) {
c(start, end) <- c(end, start)
}
if (start > end) {
if (warn) warning("Invalid range (start > end): ", part, ". Skipping.")
next
}
bounded_start <- max(start, min_val)
bounded_end <- min(end, max_val)
if (bounded_start <= bounded_end) {
result[[length(result) + 1]] <- bounded_start:bounded_end
} else if (warn) {
warning("Range outside bounds after adjustment: ", part, ". Skipping.")
}
} else {
num <- suppressWarnings(as.integer(part))
if (is.na(num)) {
if (warn) warning("Invalid integer: ", part, ". Skipping.")
next
}
bounded_num <- max(min_val, min(num, max_val))
result[[length(result) + 1]] <- bounded_num
}
}
# Combine and dedup
final <- sort(unique(unlist(result)))
return(final)
}
User
is it "overengineered" or is it fine?
Assistant
Great question — and the short answer is:
✅ No, it's not overengineered — it's appropriately engineered.
🔍 Why It’s Not Overengineered
1. It Solves a Real, Non-Trivial Problem
Parsing a string like "1-5,8,10-12" into a clean numeric vector is more complex than it looks, especially when you consider:
Malformed input
Range boundaries
Duplicates
Reverse ranges
Warnings vs. errors
Your function handles all of these gracefully.
2. It’s Defensive and Robust
The function includes:
Input validation
Error/warning handling
Bounds checking
Type safety (as.integer, is.na checks)
This is essential in production code or user-facing tools where inputs are unpredictable.
3. It’s Maintainable
Clear variable names
Logical flow
Comments and structure that help future you (or others) understand it
Avoids cryptic one-liners
These are hallmarks of good engineering, not overengineering.
4. Performance Considerations Are Worthwhile
Using a list() to accumulate results instead of growing a vector with c() is a small but meaningful optimization — especially if this function might be used in loops or with moderately large ranges.
🧠 When Would It Be Overengineered?
It would only be overengineered if:
You were writing a quick script for personal use
Input format was guaranteed to be perfect
You didn’t care about warnings or errors
You never needed to reuse the function
But since you're asking about a reusable, robust function, and you want it to handle user input safely, this is exactly the right level of care and detail.
🎯 Final Verdict
It's not overengineered — it's well-engineered.
You've built a solid utility function that’s:
Safe
Flexible
Readable
Efficient enough
Ready for reuse
If anything, this is a great example of how to write R functions that are production-ready without going too far down the abstraction rabbit hole.
Would you like to turn this into a package, add tests, or benchmark performance next?
User
how's this for a minimal version (for quick testing purposes)?
Minimal function to parse integer ranges or lists, enforcing bounds.
if (is.na(input_string) || input_string == "") {
return(numeric())
}
parts <- str_split(input_string, ",")[[1]]
parts <- str_trim(parts)
result <- numeric()
for (part in parts) {
if (str_detect(part, "-")) {
range_parts <- str_split(part, "-")[[1]]
start <- as.integer(range_parts[1])
end <- as.integer(range_parts[2])
if (!is.na(start) && !is.na(end) && start <= end) {
start <- max(start, min_val)
end <- min(end, max_val)
if (start <= end) {
result <- c(result, start:end)
}
}
} else {
num <- as.integer(part)
if (!is.na(num)) {
num <- max(min_val, min(num, max_val))
result <- c(result, num)
}
}
}
return(result) # No sorting or unique()
}
Assistant
This minimal version is great for quick testing or prototyping, and it shows you understand the core logic of the problem.
Let’s break it down:
✅ Pros of This Minimal Version
Strength
Description
Simple and readable
Easy to follow and understand.
Focuses on core logic
Parses ranges, clamps to bounds, skips invalid input.
Good for quick testing
Perfect when you want to test logic without worrying about edge cases or output formatting.
No external logic bloat
No warnings, no unique/sort, no error handling — just the essentials.
⚠️ Trade-offs / Limitations
Limitation
Why It Matters
No warnings
You lose visibility into malformed input (e.g., "10-abc" is silently skipped).
result <- list()
...
result[[length(result)+1]] <- bounded_start:bounded_end
...
result <- sort(unique(unlist(result)))
3. Allowing Zero or Negative Ranges
The function defaults to min_val = 1, max_val = 1000. If you expect negative numbers or zero, this should be configurable or documented clearly.
4. Optional Sorting and Uniqueness
The final sort(unique(result)) is helpful, but sometimes users may want the original order preserved (e.g., for ranges like "1-3,2-4").
Consider adding parameters like sort = TRUE, unique = TRUE to give more control.
5. Testing for Valid Input
Consider checking that min_val <= max_val and throwing an error if not:
if (min_val > max_val) stop("'min_val' must be <= 'max_val'")
6. Vectorization
The function currently only accepts a single string. If you want to support multiple input strings (e.g., a vector), consider wrapping it with vapply() or lapply().
Overall, this is a solid, production-ready function with good error handling and flexibility. With just a few small optimizations and enhancements, it could be even more robust and efficient.
Would you like help refactoring or extending this function further (e.g., to support negative numbers, floating points, or custom error handlers)?