Search code examples
rfunctionfunctional-programmingcryptographyassign

R building simple function with for loop, returns nothing


I have a new R package here called "crypto" to collect coin prices, I'm using it to build a simple function to source in the future, the main idea is the following:

CryptoList <- c('BTC','ETH', .....)

for (i in 1: length(CryptoList))
{
  x = CryptoList[i]
  a = crypto_history(x, start_date=start_date, end_date=end_date)
  assign (as.character(x), a)
}

It works out perfectly like this, however, when I built this into a function, it does not assign anymore.

getCryptoPrice <- function(CryptoList, start_date, end_date)
{
for (i in 1: length(CryptoList))`enter code here`
{
  x = CryptoList[i]
  a = crypto_history(x, start_date=start_date, end_date=end_date)
  assign (as.character(x), a)
}

}

getCryptoPrice(CryptoList, '20180101', '20181231')

> BTC
Error: object 'BTC' not found

It looks like the assign function is not working properly, while it will if it's not in the function. Does anybody know why?

Thanks


Solution

  • Instead of using for loop and assign another way would be to return a named list. Lists are easier to manage and avoids polluting the global environment with lot of objects.

    getCryptoPrice <- function(CryptoList, start_date, end_date) {
        output <- lapply(CryptoList, crypto::crypto_history, 
                        start_date=start_date, end_date=end_date)
        names(output) <- CryptoList
        return(output)
    }
    

    and then call it like :

    output <- getCryptoPrice(CryptoList, '20180101', '20181231')
    

    Now, you could access individual dataframes like output[['BTC']], output[['ETH']] etc.