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.
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.
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,])
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