Reputation: 15
I have a matrix called r2, and for each column of that matrix, i need to add another column of data - ie. I want the result to be the first element of the first column + the first element in the second column; second element + second element; and so on. I can get it to work when I separate one column and add it, but I can't loop over the columns of the matrix. See below:
This is the matrix r2:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 51.032 45.480 42.638 59.808 40.309 51.135
[2,] 50.591 45.415 47.962 57.020 39.670 52.518
[3,] 55.695 50.099 50.205 63.256 45.174 50.475
[4,] 46.422 44.233 44.322 53.229 34.943 41.707
[5,] 52.357 44.523 44.374 57.014 41.672 53.920
[6,] 53.610 44.448 41.846 60.451 42.163 52.706
[7,] 51.728 44.612 43.305 56.844 39.048 48.710
[8,] 52.790 45.266 43.426 58.365 41.577 54.630
and here is the column I want to add to each column of the matrix, called BDtool["Constant"]:
-26.701
-29.287
-30.964
-24.246
-29.194
-30.444
-26.524
-29.771
this code works to add a column of r2 to the Constant column:
r3 <- r2[,1]+BDtool["Constant"]
and the outcome looks like:
[1,] 24.434
[2,] 23.231
[3,] 19.511
[4,] 17.461
[5,] 24.726
[6,] 22.262
[7,] 22.186
[8,] 24.859
this is exactly what i want. However, I can't get any kind of for-loop to work. I just want to iterate over every column in r2 and, for each column, get an output like the one above. i've fiddled with various versions of:
r3 <- for (i in r2[,1:6]) {
i +BDtool["Constant"]
}
but r3 always ends up NULL. How do i make this work? Thank you for any advice you can offer!
Upvotes: 1
Views: 1411
Reputation: 368231
One way is to use a helper matrix. Say you have
> M <- matrix(1:9,3,3); M
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
>
and you want to add a vector c(1,2,3)
to each column. Well, we can create an matrix of ones and multiply it with that vector:
> idV <- matrix(1,3,3) * c(1,2,3); idV
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 2 2 2
[3,] 3 3 3
>
After that we just add the two matrices:
> M + idV
[,1] [,2] [,3]
[1,] 2 5 8
[2,] 4 7 10
[3,] 6 9 12
>
You can set that up easily in a helper function.
Edit: But as Ronan reminds us in his answer above, the recycling rule makes that automagic.
Upvotes: 1
Reputation: 388982
You can use r3 <- r2 + BDtool$Constant
This works because of R's recycling property. BDtool$Constant
is added first to the first column of r2
matrix and the values in BDtool$Constant
are recycled and reused for the second column again and so on for all other columns.
This simplified example may help clarify -
r2 <- matrix(1:18, 6, 3)
v <- 1:6
r2 + v
# [,1] [,2] [,3]
#[1,] 2 8 14
#[2,] 4 10 16
#[3,] 6 12 18
#[4,] 8 14 20
#[5,] 10 16 22
#[6,] 12 18 24
Upvotes: 3