我有一个问题,我肯定有一个简单的解决办法,但我想不出来。
背景:我已经将几个矩阵引入到R中,最初是作为一个列表,但现在它们处于“统一”矩阵中(这种格式是以后处理所必需的)。我需要对每一行执行一个计算(减去一个向量);我需要减去一个长度相同的向量。子运算的特定向量保存在32个唯一向量的列表中。
在统一矩阵中有150个数据帧,其中有32行(在统一矩阵中总共有4800行)。减法向量的长度为1021,对应于统一矩阵中相同数量的列。
dat.y <- rep(1:32, times=150)
rows <- 32d.list是由32个一维向量组成的列表,每个向量长度为1021。
mattiff是一个矩阵4800x1021,以前是150个尺寸为32x1021的tiff图像。
for (i in 1:length(dat.y)
{
for (j in 1:length(rows))
{
mattiff2<-mattiff[i, ] - d.list[[j]]
}
}本质上,我想在统一矩阵中重复32行150次子运算的循环。
可复制示例:
mm <- matrix(100, 128, 1021)
list_sub<-list()
rows<-seq(1, 32, 1)
dat.len<-seq(1, 128, 1)
dat.y<-rep(1:32, times=4)
## random data to substract from mm
for (i in 1:32)
{
list_sub[[i]]<-runif(n = 1021, min = 45, max = 80)
}
## I want this to substract list_sub[[i]] from mm[i,]
## essentially making the loop of 32 rows across all 128
## rows of mm. I.e substracting from mm rows 1...32 with list_sub
## then substracting from mm rows 33...64 with list_sub
## then subtracting from mm rows 65...96 with list_sub
## then subtracting from mm rows 97...128 with list_sub
## I would imagine an approach similar to this would give me the result I want
## to give mm_2: a matrix with the same dimensions of mm
for (i in 1:length(dat.y))
{
for (j in 1:length(rows))
{
mm_2 <- mm[i,] - list_sub[[j]]
}
}发布于 2015-03-12 12:19:30
因此,您有150个32x1021阶矩阵,统一(rbinded)在矩阵矩阵中,它是4800x1021,您想要减去行1,33,65,……d.list[1]的元素,以行2,34,66,.d.list[2]的元素等等。
我假设
mattiff2<-mattiff[i, ] - d.list[[j]]是错误的(就像可重复的例子一样),您希望mattiff2成为一个矩阵4800x1021,并得到相应的减法。
以下是一种方法:
# arrange the elements of d.list as a matrix 1021x32
d.array <- simplify2array(d.list)
# repeat d.array 150 times for a matrix 1021x4800
sub <- matrix(d.array,1021,4800)
# subtract elementwise
mattiff2 <- mattiff - t(sub)如有需要,用长度(dat.y)代替4800。
https://stackoverflow.com/questions/29007430
复制相似问题