【问题标题】:Splitting Dataset into Deciles in R在 R 中将数据集拆分为十分位数
【发布时间】:2017-03-03 01:15:33
【问题描述】:

我在制作十分位投资组合时遇到了麻烦。 This is my dataset: X 行代表 1 个会计期间,列代表公司。

我试图获取每个时期的每个分位数。

 Decile_X <- data.frame(matrix(nrow = 11, ncol = 56))
   for(i in 1:56){
    Decile_X[,i]<-as.numeric(quantile(X[i,], prob = seq(0, 1,length = 11), 
type = 5, na.rm=T))}

产生这个 Result of quantiles in each periods, column represents periods

通过这个结果,我试图在每个时期的 X 数据集中获得 0%~10%、10%~20% ... 90%~100% 之间的平均值。

Df <- data.frame(matrix(nrow = 10, ncol = 56))
 for(i in 1:nrow(TaxExpense)){
   for(j in 1:10){
     Df[j,i] <- mean(rowMeans(X[i, which(!is.na(Decile_X[i,]) & 
       X[i,]>Decile_X[j,i] & X[i,]<=Decile_X[j+1,i])], na.rm=T))

但问题是因为在 Decile_X 的某些时段中,在 40%~50%、50%~60%、60%~70% 中显示 0.000000000,所以我无法准确分割。

这个问题有什么解决办法吗? 还是我的方法制作十分位投资组合效率很低?

我是 R 新手,并试图详细解释。 请帮帮我。

【问题讨论】:

  • 您可以使用 dplyr 拆分为十分位数:mydata %>% mutate(quantile = ntile(x1, 10))。 x1 是您要用于拆分为十分位数的列。

标签: r


【解决方案1】:

我希望我能正确理解您的困境。

基本上,这就是我计算十分位数内的算术平均值的方法。但首先,我刚刚添加了一些虚拟数据,所以如果您只想将其复制到您的 R IDE 中,它应该可以作为示例而无需更改它。

# Some dummy data
c1 <- c(1:100)
c2 <- c(301:400)
c3 <- c(101:200)
c4 <- c(201:300)
df <- cbind(c1, c2, c3, c4)

这里我设置了与有多少“分区”相关的数字 quant_n,因为没有更好的词。

quant_n <- 10 # 10 for decile, 4 for quartile, et cetera.
# Function for computing mean within each part of the n-tile
quantile_ave <- function(x, y = quant_n){
    z <- 1 / y
    q = quantile(x, seq(0, 1, by = z))
    cuts = cut(x, q)
    values_per_quantile = split(x, cuts)
    calc_mean = sapply(values_per_quantile, mean)
    names(calc_mean) <- NULL
    calc_mean
}

#Here we put the quantile_ave to work on the dummy data in df
results <- matrix(0L, nrow = quant_n, ncol = ncol(df)) #Matrix to overwrite with results
for (i in 1:ncol(df)){
    results[, i] <- quantile_ave(df[, i])
}

希望对您有所帮助。

【讨论】:

  • 谢谢!我根据您的代码解决了我的问题!再次感谢~
猜你喜欢
  • 2016-04-25
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2019-08-07
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多