将数据划分为十分位数,并计算每个十分位数的平均值



我有两个维度相同的数据集。我想根据第二数据集的每一行,将第一数据集的各行划分为十分位数,然后计算每十分位数的平均值。我知道我可以在order和loops函数的帮助下做到这一点。但这需要很多时间。

x<-matrix(rnorm(10000),nrow = 100,ncol=100)
y<-matrix(rnorm(10000),nrow=100,ncol = 100)
m.r<-rep(0,100)
for (t in 1:100){
y1<-y[t,]
my_order<-order(y1,decreasing = T)
top_10<-my_order[1:10]
m.r[t]<-mean(x[t,top_10])
}
and so on next 10-20, 20-30 etc.

您可以首先创建一个列排名为y的矩阵y.order

y.order <- t(apply(y, 1, order, decreasing=TRUE))

然后按照10步的排序(用split实现(,取sapply嵌套内每行的平均值。

res <- t(sapply(1:nrow(x), function(m) 
sapply(split(1:100, rep(1:10, each=10)), function(n) 
mean(x[m, y.order[m, n]]))))

结果

head(res[,1:5])
#               1            2          3            4          5
# [1,] -0.1678216  0.102505130  0.5324668  0.344757153  0.7638530
# [2,]  0.0157764 -0.526831195 -0.3383647 -0.169914681 -0.6141832
# [3,] -0.5376350 -0.001527589 -0.2797928 -0.680547573 -0.1882390
# [4,] -0.1616552 -0.229384402  0.4574600  0.315167214 -0.1952255
# [5,] -0.0478654 -0.095276814  0.4097697 -0.003122267  0.4291888
# [6,]  0.2280566 -0.322672289 -0.5022181 -0.493842480 -0.3193979

数据

set.seed(42)
x <- matrix(rnorm(1e4), nrow=100, ncol=100)
y <- matrix(rnorm(1e4), nrow=100, ncol=100)

最新更新