Search code examples
rquantmod

chart_Series does not plot when called in function with condition that evaluates to FALSE


I am begginer with R so maybe I am missing some concept about functions. But here is my example and I am interested why it works like that?

require(quantmod);

myPlot = function(ts, addAdx = TRUE) {
  chart_Series(ts);

  if (addAdx) {
    add_TA(ADX(HLC(ts))$ADX)  
  }

}

getSymbols("DIA", src='yahoo');
myPlot(DIA, addAdx = FALSE)

If I set addAdx parameter to false then my function does not plot the chart (otherwise its fine). Why is that?


Solution

  • If you don't use return the R functions return the latest computed value.

    If addAdx is set to FALSE the function returns a void.

    This code solve your problem:

      myPlot = function(ts, addAdx = TRUE) {
      p <- chart_Series(ts);
    
      if (addAdx) {
       p <- add_TA(ADX(HLC(ts))$ADX)  
      }
    
      p #return(p)
    }