Sometimes I need to create character vectors like this one:
datanames <- c(
"europe_co2_min",
"europe_co2_max",
"europe_temperature_min",
"europe_temperature_max",
"asia_co2_min",
"asia_co2_max",
"asia_temperature_min",
"asia_temperature_max"
)
Notice that this is actually the Cartesian product of the character vectors joined together with a _
:
c('europe', 'asia')
c('co2', 'temperature')
c('min', 'max')
I came up with this helper function:
combine <- function(..., prefix='', sep='_') {
combine.inner <- function(lx, ...) {
if (length(c(...)) > 0) {
sapply(sapply(lx, function(x) paste(x, combine.inner(...), sep=sep)), c)
} else {
lx
}
}
paste(prefix, combine.inner(...), sep='')
}
It handles arbitrary number of character vector parameters of arbitrary lengths. The prefix
parameter is for convenience. It's similar to having a single element vector as the first parameter, except the common separator sep
will not be applied after it.
- Is there an easier way that exists in R and I missed?
- Is there anything smelly about this code?