title: Append Object IF Specified to Data Frame: Errors in User Defined Function-R
body: <p>I'm having trouble trying to get an if else statement to work. Essentially, what I want it to do is as follows: if my object (z) exists then append to my data frame (results &lt;- data.frame(x, y, z)), else do nothing (thus results &lt;- data.frame(x, y)). </p>
  
  <p>Below is a reproducible example of what I'm trying to accomplish:</p>
  
  <h1>Reproducible example</h1>
  
  <pre><code>library(forecast) 
  
  
  set.seed(1234)
  testData &lt;- rnorm(1000)
  
  mFits &lt;- function(data, mod1, mod2 = NULL, mod3 = NULL) {
  
    # Must at least choose one model to evaluate
    # If mod2, mod3 are specified in the arguments then evaluate 
    m1 &lt;- mod1(data)$fitted
  
    if (!is.null(mod2)) {
      m2 &lt;- mod2(data)$fitted
    }
  
    if (!is.null(mod3)){
      m3 &lt;- mod3(data)$fitted
    }
  
    # Put fitted values into a data frame
  
    if (!is.ts(m2)) {
      fits &lt;- data.frame(m1)
    }
    else {
      fits &lt;- data.frame(m1, m2)
    }
  
    if (!is.ts(m3)) {
      fits &lt;- data.frame(m1)
    }
    else {
      fits &lt;- data.frame(m1, m3)
    }
  
  }
  
  modelFit &lt;- mFits(testData, mod1 = auto.arima, mod2 = NULL, mod3 = NULL)
  Error in is.ts(m3) : object 'm3' not found
  </code></pre>
  
  <p>However, I keep getting an error, like the one above. I know m3 does not exists because I did not specify it to exist. Essentially, what I want is a data frame that must have the fitted values from m1, and optionally have the fitted values from m2 and m3 appended if they are specified in the arguments of the function. Could someone point me in the right direction? I'm a bit unsure of what to do next. </p>
  
  <p>Thanks </p>