title: R ~ Vectorization of a user defined function
body: <p>I need to write a function that will count the number of working days (minus weekends, and a vector of other local bank holidays), but the problem I'm coming up against is more simply illustrated with just counting the number of weekdays.</p>
  
  <p>Here is a function that will give the number of weekdays between two dates:</p>
  
  <pre><code>removeWeekends &lt;- function(end, start){
  
    range &lt;- as.Date(start:end, "1970-01-01")
  
    range&lt;- range[sapply(range, function(x){
                                  if(!chron::is.weekend(x)){
                                    return(TRUE)
                                  }else{
                                    return(FALSE)
                                  }
                                })]
  
    return(NROW(range))
  
  }
  </code></pre>
  
  <p>Which works when it is given a single date for each argument:</p>
  
  <pre><code>removeWeekends(as.Date("2018-05-08"), as.Date("2018-06-08"))
  #[1] 24
  </code></pre>
  
  <p>But when it is given a two vectors from a data frame it fails:</p>
  
  <pre><code>one &lt;- as.Date("2017-01-01"):as.Date("2017-01-08")
  two &lt;- as.Date("2018-06-08"):as.Date("2018-06-15")
  df &lt;- data.frame(one, two)
  removeWeekends(df$two, df$one)
  #[1] 375
  #Warning messages:
  #1: In start:end : numerical expression has 8 elements: only the first used
  #2: In start:end : numerical expression has 8 elements: only the first used
  </code></pre>
  
  <p>I've also tried (which I guessed would not work as the syntax seems off): </p>
  
  <pre><code>lapply(df, removeWeekends, df$two, df$one)
  #Error in FUN(X[[i]], ...) : unused argument (17167:17174)
  </code></pre>
  
  <p>And:</p>
  
  <pre><code>lapply(df[,c("two", "one")], removeWeekends)
  #Error in as.Date(start:end, "1970-01-01") :   argument "start" is missing,
  # with no default 
  </code></pre>
  
  <p>I'm assuming it is me misunderstanding the concept of vectorization.</p>
  
  <p>The only other idea I've got is nesting the function within a conditional to see if it's a vector, then calling an apply function on it if it is although I'm not quite sure how I would structure that either.</p>