Search code examples
rlapplyxtsquantmod

How to loop through objects in the global environment - R


I have looked far and wide for a solution to this issue, but I cannot seem to figure it out. I do not have much experience working with xts objects in R.

I have 40 xts objects (ETF data) and I want to run the quantmod function WeeklyReturn on each of them individually.

I have tried to refer to them by using the ls() function:

lapply(ls(), weeklyReturn) 

I have also tried the object() function

lapply(object(), weeklyReturn)

I have also tried using as.xts() in my call to coerce the ls() objects to be used as xts but to no avail.

How can I run this function on every xts object in the environment?

Thank you,


Solution

  • It would be better to load all of your xts objects into a list or create them in a way that returns them in a list to begin with. Then you could do results = lapply(xts.list, weeklyReturn).

    To work with objects in the global environment, you could test for whether the object is an xts object and then run weeklyReturn on it if it is. Something like this:

    results = lapply(setNames(ls(), ls()), function(i) {
      x = get(i)
      if(is.xts(x)) {
        weeklyReturn(x)
      }
    })
    
    results = results[!sapply(results, is.null)]
    

    Or you could select only the xts objects to begin with:

    results = sapply(ls()[sapply(ls(), function(i) is.xts(get(i)))],
           function(i) weeklyReturn(get(i)), simplify=FALSE, USE.NAMES=TRUE)
    

    lapply(ls(), weeklyReturn) doesn't work, because ls() returns the object names as strings. The get function takes a string as an argument and returns the object with that name.