1

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.

3
  • 2
    Just remove the trade_time at the end. i.e. you just need quantmod::getQuote(ticker)$'Trade Time' Commented Dec 21, 2022 at 21:33
  • may I ask when am I required to put the return variable after the function is written, or in the case, where I am not required to put the return variable? Thanks Akrun Commented Dec 21, 2022 at 21:49
  • 1
    In R, the value of the last statement in the function in returned by default unless you have a return before that line. i.e suppose you have a function f1 <- function(x) {if(x > 10) {return("Yes"); "hello"}; return("Not TRUE")} The default case is returned if it is not TRUE i.e. f1(5) [1] "Not TRUE" and the other case f1(11)# [1] "Yes" Note that here we provided return, so the last statement with "hello" is not returned Commented Dec 21, 2022 at 21:52

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.