有效地对通过不同矩阵相关的整行求和
Efficiently sum entire rows which are related through a different matrix
我的代码的目标是创建一个新矩阵 BySite
,其中行是 LOLZ
行的总和(我正在使用 colSums()
),这些行在 XY
矩阵。因此,如果两个 XY
行匹配,那么我希望新矩阵有一行,它将相关的(根据 XY
)LOLZ
行相加。
BySite<-matrix(0,dim(unique(XY))[1],dim(LOLZ)[2]);
BySite[1,]<-LOLZ[1,];
for (i in 1:dim(unique(XY))[1]){
tree<-which(apply(XY, 1, function(x) all(x == unique(XY)[i,]))==TRUE)
if (length(tree)==1){
BySite[i,]<-LOLZ[tree,]
}
else {
BySite[i,]<-colSums(LOLZ[tree,])
}
cat(i," *sigh*")
}
XY
是纬度和经度矩阵,因此可以使用:
XY<-matrix(c(rep(c(55:74),100),rep(c(101:120),100)),2000,2)
而对于 LOLZ
LOLZ<-matrix(abs(rnorm(2000*50)),2000,50)
我的代码可以运行,但速度慢得令人痛苦,正在寻求一些建议以使其更快。
这是对较小数据集的尝试:
XY = cbind(rep(50:55, 3), rep(100:105, 3))
set.seed(007); LOLZ = matrix(sample(1:5, 18 * 5, T), 18, 5)
paste_XY = paste(XY[, 1], XY[, 2], sep = "; ") #or apply(XY, 1, paste, collapse = "; ")
ans = rowsum(LOLZ, paste_XY)
#after running your code to build "BySite"
sum(ans != BySite)
#[1] 0
我的代码的目标是创建一个新矩阵 BySite
,其中行是 LOLZ
行的总和(我正在使用 colSums()
),这些行在 XY
矩阵。因此,如果两个 XY
行匹配,那么我希望新矩阵有一行,它将相关的(根据 XY
)LOLZ
行相加。
BySite<-matrix(0,dim(unique(XY))[1],dim(LOLZ)[2]);
BySite[1,]<-LOLZ[1,];
for (i in 1:dim(unique(XY))[1]){
tree<-which(apply(XY, 1, function(x) all(x == unique(XY)[i,]))==TRUE)
if (length(tree)==1){
BySite[i,]<-LOLZ[tree,]
}
else {
BySite[i,]<-colSums(LOLZ[tree,])
}
cat(i," *sigh*")
}
XY
是纬度和经度矩阵,因此可以使用:
XY<-matrix(c(rep(c(55:74),100),rep(c(101:120),100)),2000,2)
而对于 LOLZ
LOLZ<-matrix(abs(rnorm(2000*50)),2000,50)
我的代码可以运行,但速度慢得令人痛苦,正在寻求一些建议以使其更快。
这是对较小数据集的尝试:
XY = cbind(rep(50:55, 3), rep(100:105, 3))
set.seed(007); LOLZ = matrix(sample(1:5, 18 * 5, T), 18, 5)
paste_XY = paste(XY[, 1], XY[, 2], sep = "; ") #or apply(XY, 1, paste, collapse = "; ")
ans = rowsum(LOLZ, paste_XY)
#after running your code to build "BySite"
sum(ans != BySite)
#[1] 0