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 e.g. 1-3 = -2 & 2-3 =-1 Do get a good understanding of R programming, I would like to create a for loop. 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. The purpose is to learn more about R programming. Thanks
This is a good case for sweep:
sweep(z, 1, c)
# A B
#[1,] -2 -1
#[2,] -4 -2
#[3,] -6 -3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With