Home > Mobile >  function not displaying an output in R
function not displaying an output in R

Time:12-22

I know the header sounds confusing but thats what I have now:

ticker<-c("AAPL","TSLA")
quantmod::getQuote(ticker)$'Trade Time'

[1] "2022-12-21 16:00:04 EST" "2022-12-21 16:00:04 EST"

The above line works normally, however, when I turn this line to a function like below:

trade_time<-function(ticker){
  quantmod::getQuote(ticker)$'Trade Time'
  trade_time
}

The output is as follows:

> trade_time(ticker)
function(ticker){
  quantmod::getQuote(ticker)$'Trade Time'
  trade_time
}

May I know what is the function missing in order to show the output? Many thanks.

CodePudding user response:

trade_time is the function created. We need to return the value i.e.

trade_time<-function(ticker){
   quantmod::getQuote(ticker)$'Trade Time'
}

-testing

trade_time(ticker)
[1] "2022-12-21 16:00:04 EST" "2022-12-21 16:00:04 EST"

Just to show an example how the return works i.e. in R, the last statement output is returned even if we don't explicitly mention return. But, we can use return before the last line as well e.g. to print or do something else

f1 <- function(x) 
   {
     if(x > 10) 
         {
          return("Yes")
         "hello"
       }
  return("Not TRUE")
}

In this function, we only have an if case and a default return if the expression is not satisfied. Also, note that the "hello" is the last statement within the if block, but it is not returned as there is an explicit return before that line

> f1(5)
[1] "Not TRUE"
> f1(11)
[1] "Yes"
  • Related