Reputation: 7840
I have two lists of parameters, one list contains the parameters value (parameters
in the exemple below) and the other one contains all the enumerated values that each parameter can take (parameters.enum
).
Parameters aren't mandatory so they can be NULL
. All parameters aren't defined in parameters.enum
, if the parameter is missing in parameters.enum
then there is no restricted values for this parameter.
parameters.enum <- list(a = c("a1", "a2"),
b = c("b1", "b2"),
c = "c1")
parameters <- list(a = "a1", #allowed
b = "a1", #not allowed
c = NULL, #allowed
d = "aaa") #allowed
For each non NULL
parameter in parameter
and defined in parameters.enum
I would like to check if they take a valid value. If not I would like to display a message, for exemple : 'b' should be one of "b1", "b2"
.
At the moment I use a loop to achieve what I want :
for (i in seq_along(parameters)) {
j <- which(names(parameters.enum) == names(parameters[i]))
if (length(j) != 0L && !is.null(parameters[[i]]) && !parameters[[i]] %in% parameters.enum[[j]]) {
cat("Parameter \'", names(parameters[i]), "\' should be one of ", paste0("\"", parameters.enum[[j]], "\"", collapse = ", "), sep = "")
}
}
But I feel like there could be a more straightforward and elegant way to achieve this, do you have any ideas ? Thanks !
Upvotes: 1
Views: 81
Reputation: 40648
Here's a method that loops over your parameters and uses match.arg
. The result is a list that can be used for further processing:
results <- lapply(names(parameters), function(i) {
if (!is.null(parameters.enum[[i]])) {
try(match.arg(parameters[[i]], parameters.enum[[i]]))
}
})
Upvotes: 2