perform a function in a list in R

Viewed 21

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

1 Answers

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, e.g. library(mypackage), or you can prepend the package to the function call, e.g. 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
Related