R使用for循环构建简单函数,不返回任何内容
我在这里有一个新的R包,名为crypto,用于收集硬币价格,我正在使用它构建一个简单的函数,以在将来获取来源,主要思想如下:R使用for循环构建简单函数,不返回任何内容,r,function,functional-programming,cryptography,assign,R,Function,Functional Programming,Cryptography,Assign,我在这里有一个新的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),
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)
}
赋值函数似乎工作不正常,但如果它不在函数中,则会正常工作。有人知道为什么吗
谢谢,不用for循环和赋值,另一种方法是返回命名列表。列表更易于管理,并避免使用大量对象污染全球环境
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')
现在,您可以访问各个数据帧,如输出['BTC']]、输出['ETH']]等。。使用return从函数返回对象。或者隐式返回最后一个对象。
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')