Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an array in R, how can we conduct subtraction in each element of the array?

Tags:

r

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.

like image 676
user321627 Avatar asked May 31 '18 03:05

user321627


2 Answers

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.

like image 159
mt1022 Avatar answered Sep 20 '22 22:09

mt1022


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,])
like image 33
PKumar Avatar answered Sep 18 '22 22:09

PKumar