2

I am learning to use R for an econometrics project at the university, so forgive my n00bness

basically, using and given - a matrix "stocks prices" (rows = days, coloumns = firm's stock price) - another matrix "market capitalisation" (rows = days, coloumns= firm's market cap), I have to gather in a third matrix the prices of the shares belonging to the first quintile of the distribution of the market capitalisation for every day of observation and then I have to put the mean of the "small caps" in a fourth vector. the professor I am working for suggested me to use the quintile function, so my question is... how do I get if the "i" stock belongs to the first or the last quintile? thanks for the forthcoming help!

for (i in 1:ndays){
  quantile(marketcap[i,2:nfirms],na.rm=TRUE)
  for (j in 1:nfirms){
  if marketcap[j,i] #BELONGS TO THE FIRST QUINTILE OF THE MARKETCAPS
      thirdmatrix <- prices[i,j]
  }
  fourthvector[i] <- mean(thirdmatrix[i,])
}
Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187

1 Answers1

6

Here's a way to find out to which quintile a value belongs. Note that I used a quintile with "open" ends, i.e., each value belongs to exactly one quintile.

a <- 2:9  # reference vector
b <- 1:10 # test vector

quint <- quantile(a, seq(0, 1, 0.2)) # find quintiles
#   0%  20%  40%  60%  80% 100% 
#  2.0  3.4  4.8  6.2  7.6  9.0 

# to which quintile belong the values in 'b'?
findInterval(b, quint, all.inside = TRUE)
# [1] 1 1 1 2 3 3 4 5 5 5
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • so basically I have to apply findInterval and ask if the resultant value is 1? like [ x <- findInterval(marketcap[i,j],quint,all.inside=TRUE) if x == 1 then etc etc] .......would that work? – user3341312 Feb 23 '14 at 11:07