我这里有一个新的R包,叫做“ crypto”,用于收集硬币价格,我正在用它来构建一个简单的函数以供将来使用,主要思想如下:
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)
}
它完全像这样工作,但是,当我将其内置到函数中时,它不再分配。
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
似乎assign函数无法正常运行,如果不在函数中,它将正常运行。有人知道为什么吗?
谢谢
答案 0 :(得分:1)
代替使用for
循环和assign
,另一种方法是返回一个命名列表。列表更易于管理,并且避免了污染很多对象的全局环境。
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)
}
然后将其命名为:
output <- getCryptoPrice(CryptoList, '20180101', '20181231')
现在,您可以访问output[['BTC']]
,output[['ETH']]
等单个数据帧。