How to get the x which belongs to a quintile?

岁酱吖の 提交于 2020-01-15 06:26:12

问题


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,])
}

回答1:


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


来源:https://stackoverflow.com/questions/21958324/how-to-get-the-x-which-belongs-to-a-quintile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!