lundi 25 avril 2016

How to collect observation from one vector, conditioned to the value of another one

I have the following problem: I am considering a database of 10 different vectors, containing the return of the same number of portfolios. I want to split the sample in two subsets, one containing the returns when the market performed positively, and the other containing the returns when the market performed badly. For this reason I have another vector containing the return of the market.

What I did so far is this:

a) I have computed the number of days in which the market had positive or negative returns:

n_bull <- sum(Mkt_Ret >= 0 )
n_bear <- sum(Mkt_Ret <  0 )

b) I have created a series of vector that will contain the result for each portfolio, i.e.:

Portfolio_1_Bull <- rep(0, n_bull)
Portfolio_1_Bear <- rep(0, n_bear)

c) I run a loop to fill the latter with a loop:

for(i in 1:length(Portfolio_1_EW_tot_ret)){
  if(Mkt_Ret[i] >= 0){
   Portfolio_1_Bull[i] = Portfolio_1_EW_tot_ret[i]
  } 
 }
}

The problem is that the resulting vector Portfolio_1_Bull will have the same number of observation of the whole portfolio. Is there a way to solve this problem?

Aucun commentaire:

Enregistrer un commentaire