Home > other >  Unable to store data in a function
Unable to store data in a function

Time:03-03

getSymbols(c("spy", "XLE", "IYR", "XLP", "XLY", "XLV", "XLK", "XLF", "XLU","IYR","XLI", "XLC", "XME"))

  
get.sector.performance <- function(interval) {
  
  year <- "2021::"
  
  sp500 <- cumsum(interval(SPY[year]))

}

get.sector.performance(dailyReturn)

The problem is it doesn't store value in sp500 variable. I don't see the sp500 data in global environment.

CodePudding user response:

You can use <<- instead of <- in order to write an object from a function scope to the global environment.

get.sector.performance <- function(interval) {
  
  year <- "2021::"
  
  sp500 <<- cumsum(interval(SPY[year]))

}

get.sector.performance(dailyReturn)
sp500

It is not recommended to use <<- in this context, but I think it is fine if this is a one-off thing. If the code is part of a more complex operation, a purely functional (as in not making use of side-effects) approach would be better:

get.sector.performance <- function(interval) {
  
  year <- "2021::"
  
  cumsum(interval(SPY[year]))

}

sp500 <- get.sector.performance(dailyReturn)

CodePudding user response:

Using 'local` with a defined environment would be more straightforward.

pesky_results <- new.env()
local({
    getSymbols(
        c(
            "spy",
            "XLE",
            "IYR",
            "XLP",
            "XLY",
            "XLV",
            "XLK",
            "XLF",
            "XLU",
            "IYR",
            "XLI",
            "XLC",
            "XME"
        )
    )
    res <- get.sector.performance(dailyReturn)
},envir = pesky_results)

You will be able to access the res object like that pesky_results$res. Using <<- in a function call is generally not advised if you want to access parent environment directly as this makes the function less usable. Consider a scenario where that function may be deployed within map_* or another function, you may be then exporting objects to the unintended environment. If your desire is to return the results to a specific environment, it's better to control that behaviour through use of local/eval so the environment for the results is defined explicitly.

  •  Tags:  
  • r
  • Related