Julien Navarre Julien Navarre - 5 months ago 19
R Question

Comparing elements of two different lists

I have two lists of parameters, one list contains the parameters value (

in the exemple below) and the other one contains all the enumerated values that each parameter can take (

Parameters aren't mandatory so they can be
. All parameters aren't defined in
, if the parameter is missing in
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
parameter in
and defined in
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 !


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]]))