[英]subtract two matrices in r
I have created two matrices as followings: 我创建了两个矩阵如下:
A = c(1,2,3)
B = c(2,4,6)
c = as.matrix(c(3,6,9))
z = as.matrix(cbind(A, B))
Now I want to take the matrix c and subtract it row by row eg 1-3 = -2 & 2-3 =-1 Do get a good understanding of R programming, I would like to create a for loop. 现在我想取矩阵c并逐行减去它,例如1-3 = -2和2-3 = -1对R编程有一个很好的理解,我想创建一个for循环。 PLEASE ALL YOUR ANSWERS SHOULD IMPROVE MY FOR LOOP.
请你所有的答案都应该改善我的循环。
for (i in 1:nrow(z))# for the rows in matrix z
for (j in 1:nrow(c)) # for the rows in matrix c
{
sub = matrix(NA, 3,2) # make a placeholder
sub [i,]= z[i,]-c[j,] # i am not sure whether this right
return((sub))
}
I get the following error: 我收到以下错误:
Error: no function to return from, jumping to top level
I believe my for loop is wrong, can anyone help. 我相信我的for循环是错误的,任何人都可以提供帮助。 The purpose is to learn more about R programming.
目的是了解有关R编程的更多信息。 Thanks
谢谢
This is a good case for sweep
: 这是一个很好的
sweep
案例:
sweep(z, 1, c)
# A B
#[1,] -2 -1
#[2,] -4 -2
#[3,] -6 -3
If you write your loop that way: 如果以这种方式编写循环:
sub = matrix(NA, 3,2) # make a placeholder
for (i in 1:nrow(z))# for the rows in matrix z
for (j in 1:nrow(c)) # for the rows in matrix c
{
sub [i,]= z[i,]-c[j,] # i am not sure whether this right
}
sub
it will end without error but you'll get: 它会没有错误地结束,但你会得到:
[,1] [,2]
[1,] -8 -7
[2,] -7 -5
[3,] -6 -3
which is not what you expected... because the last j was always 3 so you replaced sub[i,]
by z[i,]-c[3,]
which is z[i,]-9
这不是你所期望的...因为最后的j总是3所以你用
z[i,]-c[3,]
替换sub[i,]
z[i,]-c[3,]
这是z[i,]-9
Now if you replace the loops by : 现在,如果你用以下方法替换循环:
for (i in 1:nrow(z)) #(nrow(z)==nrow(c))
{
sub [i,]= z[i,]-c[i,]
}
then you'll have: 然后你会有:
[,1] [,2]
[1,] -2 -1
[2,] -4 -2
[3,] -6 -3
although not recommended, this will work 虽然不推荐,但这将有效
sub = matrix(NA, 3,2)
for (i in 1:nrow(z)) {
sub[i,]=z[i,]-c[i,1]
}
you don't need the second loop, also c is a column matrix. 你不需要第二个循环,c也是一个列矩阵。
You could also just create a matrix where both columns are given by c
: 你也可以创建一个矩阵,其中两列都由
c
给出:
z - cbind(c, c)
## A B
## [1,] -2 -1
## [2,] -4 -2
## [3,] -6 -3
This won't be a convenient solution for a matrix with many columns. 对于具有多列的矩阵,这不是一种方便的解决方案。 You could use
cbind
together with do.call
to have more flexibility: 您可以将
cbind
与do.call
一起使用以获得更大的灵活性:
z - do.call(cbind, rep(list(c), 2))
It is necessary to put c
in a list. 有必要将
c
放入列表中。 Otherwise, rep(...)
will return a single vector instead of a list of column matrixes: 否则,
rep(...)
将返回单个向量而不是列矩阵列表:
rep(c, 2)
## [1] 3 6 9 3 6 9
rep(list(c), 2)
## [[1]]
## [,1]
## [1,] 3
## [2,] 6
## [3,] 9
##
## [[2]]
## [,1]
## [1,] 3
## [2,] 6
## [3,] 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.