简体   繁体   English

在 R 的列表中执行 function

[英]perform a function in a list in R

I want to perform a function on my list, calculating the returns for my tickers.我想在我的列表中执行 function,计算我的代码的回报。 The aim is to add a column for each ticker in my list.目的是为我列表中的每个代码添加一列。

ticker = c("BTC-USD", "^GDAXI")
Stocks = lapply(ticker, getSymbols, source = "yahoo", auto.assign = FALSE)
names(Stocks) = ticker
Return_cal = function(x) {
  x$Return_log = periodReturn(x[,1], period = "daily", type = "log")
}

How can I perform the return calculation for each element in my list, having at the end a column for each ticker?如何为列表中的每个元素执行返回计算,最后每个代码都有一列?

Thank you谢谢

Please make sure to refer to functions with their respective package if they are not in the standard installation of R.如果不在 R 的标准安装中,请务必参考各自的 package 功能。 For instance, we cannot know what getSymbols() does and what its output looks like since we do not know where you got that function from.例如,我们不知道getSymbols()做了什么以及它的 output 是什么样子,因为我们不知道你从哪里得到 function。 Same thing for periodReturn . periodReturn

You can indicate the package by either loading it in advance, eg library(mypackage) , or you can prepend the package to the function call, eg mypackage::funnyfunction() .您可以通过预先加载它来指示 package,例如library(mypackage) ,或者您可以将 package 预先添加到 ZC1C425268E68385D1AB5074C17A94F14 函数调用(例如mypackage::funnyfunction()中。

Now, I assume that getSymbols() returns a matrix or data frame such that the first column can be used as an argument in periodReturn(x[,1], ...) .现在,我假设getSymbols()返回一个矩阵或数据框,以便第一列可以用作periodReturn(x[,1], ...)中的参数。 Then you can apply periodReturn() with your desired arguments to each element in Stocks as follows:然后,您可以将periodReturn()与所需的 arguments 应用于Stocks中的每个元素,如下所示:

ticker <- c("BTC-USD", "^GDAXI")
Stocks <- lapply(ticker, getSymbols, source = "yahoo", auto.assign = FALSE)
names(Stocks) <- ticker
Return_cal <- function(x) {
  # this only adds the new column to x but the function does not return anything yet:
  x$Return_log <- periodReturn(x[,1], period = "daily", type = "log")
  x # this returns x
}
Stocks <- lapply(Stocks, Return_cal) # apply Return_cal to each element of Stocks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM