0

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

MAXWILL
  • 27
  • 4
  • 2
    [Don't use `assign`](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad). Use `return` to return an object from the function. Or have the last object returned implicitly. – Maurits Evers Feb 26 '20 at 00:33

1 Answers1

1

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213