Arrays 计算R中三维数组的平均值

Arrays 计算R中三维数组的平均值,arrays,r,Arrays,R,我从4个pls模型中提取系数并取平均值。我想创建一个新模型,作为4个模型之一的副本,并用平均值替换系数,以预测新数据。我知道交叉验证的正确设置可以为我做到这一点,但我现在只想破解它。我的问题发生在我尝试预测时,对象维度的系数不正确 在本例中,我提取了四个维度为[1:151,1,1:21]的arraysm_reg_coef。这些pls模型有151个x变量和21个分量或潜在变量。在我用下面的代码进行平均后,我得到一个数据帧[1:151,1:21]。。。。如何在保持正确尺寸的同时求四个阵列的平均值?。

我从4个pls模型中提取系数并取平均值。我想创建一个新模型,作为4个模型之一的副本,并用平均值替换系数,以预测新数据。我知道交叉验证的正确设置可以为我做到这一点,但我现在只想破解它。我的问题发生在我尝试预测时,对象维度的系数不正确

在本例中,我提取了四个维度为[1:151,1,1:21]的arraysm_reg_coef。这些pls模型有151个x变量和21个分量或潜在变量。在我用下面的代码进行平均后,我得到一个数据帧[1:151,1:21]。。。。如何在保持正确尺寸的同时求四个阵列的平均值?。。。我希望将这四个数组平均为[1:151,1,1:21]维的输出


多亏了克里斯·霍尔布鲁克的评论,这才是对我有用的答案

library(abind)

#bind the four arrays into one array
arr = abind(m1_reg_cof,m2_reg_cof, m3_reg_cof, m4_reg_cof, along = 2)
dim(arr)
[1] 151   4  21

#average the four
abds <- apply( arr,  c(1,3), mean)
dim(abds)
[1] 151  21

#rehsape the output to match original
abds2 <- array(abds, dim = c(dim(abds)[1], 1, dim(abds)[2]))
dim(abds2)
[1] 151   1  21  
添加属性…维度名称还需要与原始名称长度相同

#none of the names changed so I can just copy them
dimnames(abds2) <- dimnames(PLSR_model_1$coefficients)

#copy the model
New_plsr_model <- PLSR_model_1

#replace the coefficients
New_plsr_model$coefficients <- (abds2)

#Predict the values of new observations (not seen in the training set)
test_predicted_1 <- predict(New_plsr_model, ncomp = 21, newdata = test_data_1)

成功

嗯,有一个拼写错误。这么简单吗?你在找什么?applyarr,c1,2,平均值代替c1,3@42我不知道你所说的二级是什么意思,那是指外部验证吗?我试图用同样类型的模型测试新数据:偏最小二乘法PLS,唯一的区别是我想从之前创建的四个模型的平均值中创建我自己的回归系数…这是否回答了你的问题?@thelatemail。。。没有applyarr,c1,2,mean给出[1:152,1:4]的数据帧,您是否尝试过简单地重塑ABD;e、 g.,abds2
library(abind)

#bind the four arrays into one array
arr = abind(m1_reg_cof,m2_reg_cof, m3_reg_cof, m4_reg_cof, along = 2)
dim(arr)
[1] 151   4  21

#average the four
abds <- apply( arr,  c(1,3), mean)
dim(abds)
[1] 151  21

#rehsape the output to match original
abds2 <- array(abds, dim = c(dim(abds)[1], 1, dim(abds)[2]))
dim(abds2)
[1] 151   1  21  
#none of the names changed so I can just copy them
dimnames(abds2) <- dimnames(PLSR_model_1$coefficients)

#copy the model
New_plsr_model <- PLSR_model_1

#replace the coefficients
New_plsr_model$coefficients <- (abds2)

#Predict the values of new observations (not seen in the training set)
test_predicted_1 <- predict(New_plsr_model, ncomp = 21, newdata = test_data_1)