Reputation: 2564
I currently have an array which is:
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
new.array <- array(c(vector1,vector2),dim = c(3,3,100))
print(new.array)
, , 1
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
, , 2
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
...
I am wondering how I can subtract just the second from the third row in each matrix, while preserving the array structure. For example I would like to obtain:
, , 1
[,1] [,2] [,3]
[1,] -6 1 1
, , 2
[,1] [,2] [,3]
[1,] -6 1 1
...
Thanks.
Upvotes: 6
Views: 492
Reputation: 17299
This will do it:
new.array[3, , , drop = FALSE] - new.array[2, , , drop = FALSE]
The drop = FALSE
is to make sure that the subset of array has the same dimensions as the original array.
Upvotes: 8
Reputation: 11128
You can do this:
If you run a dim(new.array)
it will return three dimesions in order of row, column and last dimension which represents your number of matrices .To access any particular matrix in order. You have to do : array[,,1] will fetch first matrix of that particular array and so on. In this case the total number of matrices formed is 100. Run a dim(new.array)
and see for yourself. Using lapply
on these 100 small matrices. you can subtract the third row from second row. like below.
> lapply(1:100, function(x)new.array[,,x][2,] - new.array[,,x][3,])
Upvotes: 5