mercredi 16 mai 2018

And/or multiple optional arguments in function - R

I'm trying to create a function with two arguments, where it needs the input of at least one of them. Let's suppose a function with arguments a and b:

  • If you give only a, it will give you a.
  • If you give only b, it will give you b.
  • If you give a and b, it will give you a&b
  • Anything else, it gives you "Error"

My current code (I'm trying to filter a df by month and/or day, but first I'm checking if the function works):

function.month_weekday <- function(month, weekday){
  ifelse (month %in% 1:4 & weekday %in% 1:5, month&weekday, 
          ifelse (month %in% 1:4 & is.null(weekday), month,
                  ifelse (is.null(month) & weekday %in% 1:5, weekday,
                          "Error")))
}

The problem I'm having is how can I put both arguments as optional with the mandatory of at least one? is.null() doesn't seem to works, as also == NULL or == var(0).

Aucun commentaire:

Enregistrer un commentaire