如何获得属于五分之一的x? [英] How to get the x which belongs to a quintile?
问题描述
我正在大学里学习将 R 用于计量经济学项目,所以请原谅我的不快
I am learning to use R for an econometrics project at the university, so forgive my n00bness
基本上,使用和给定 - 矩阵股票价格"(行 = 天数,列 = 公司的股票价格) - 另一个矩阵市值"(行 = 天,列 = 公司的市值),我必须收集第三个矩阵是属于每天观察的市值分布的第一个五分之一的股票的价格,然后我必须将小型股"的平均值放入第四个向量中.我工作的教授建议我使用 quintile 函数,所以我的问题是......如果i"股票属于第一个或最后一个五分位数,我如何获得?感谢即将到来的帮助!
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,])
}
推荐答案
这是找出值属于哪个五分之一的方法.请注意,我使用了一个带有开放"端的五分位数,即每个值都只属于一个五分位数.
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
这篇关于如何获得属于五分之一的x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!