[R-SIG-Finance] getting a subset corresponding to a list element

Enrico Schumann es at enricoschumann.net
Mon May 29 09:49:31 CEST 2017

Zitat von Michael Ashton <m.ashton at enduringinvestments.com>:

> I'm not sure how to ask this with the proper terminology, but here goes:
> The BDH() function in RBLPAPI returns, for a list of symbols (e.g.,  
> 'SPX Index','RIY Index','IBM Equity') a list of closing prices. The  
> problem is that the result is not a matrix or a dataframe, but a list.
> So, if I run the query with 3 symbols, I get a list with 3 elements.  
> For example, in this case, if
> symbolist <-c("SPX Index","MXWO Index","MXEA Index")
> resultlist <- bdh(symbollist, "PX_LAST",  
> options=opt,start.date=as.Date(begdate))
> then resultlist is a list with 3 elements, and as many rows as there  
> are dates between "begdate" and today (or as many month-ends, if  
> "opt" declares monthly periodicity). Suppose in this case I've set  
> this up to retrieve 60 dates.
> But I don't WANT a list. I want a zoo object containing each of  
> these as an element. I thought about starting by trying to put each  
> element in a matrix by
> data<-matrix(nrow=60,ncol=length(symbollist))
> and then looping through from 1 to length(symbolist), letting
> data[,i] <- resultlist$symbollist[i][,2]
> but this clearly doesn't work since what I really want is
> data[,1] <-resultlist$'SPX Index'[,2]
> data[,2] <-resultlist$'MXWO Index'[,2]
> etc
> But there's probably a much easier way to do this.
> I am sending this to both the general help list and the  
> r-sig-finance list since there is probably both a general way to  
> stuff a list into a zoo object and a way to do it cleanly with the  
> BDH() command. Thanks in advance for help.
> Mike

Try this:


   res <- bdh(c("SPX Index","MXWO Index","MXEA Index"),
              fields = "PX_LAST",
              start.date = as.Date("2017-01-01"),
              end.date = as.Date("2017-01-05"))

           lapply(res, function(x) zoo(x[[2]], x[[1]])))

Enrico Schumann
Lucerne, Switzerland

More information about the R-SIG-Finance mailing list