简体   繁体   中英

perform a function in a list in R

I want to perform a function on my list, calculating the returns for my tickers. 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. 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. Same thing for 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() .

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], ...) . Then you can apply periodReturn() with your desired arguments to each element in Stocks as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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