Array: subtract by line

How can I subtract the vector of each row in an array?

a <- array(1:8, dim=c(2,2,2)) a , , 1 [,1] [,2] [1,] 1 3 [2,] 2 4 , , 2 [,1] [,2] [1,] 5 7 [2,] 6 8 

Using apply gives me:

 apply(a,c(1,2), '-',c(1,5)) , , 1 [,1] [,2] [1,] 0 1 [2,] 0 1 , , 2 [,1] [,2] [1,] 2 3 [2,] 2 3 

I am trying to get:

 , , 1 [,1] [,2] [1,] 0 -2 [2,] 1 -1 , , 2 [,1] [,2] [1,] 4 2 [2,] 5 3 

Thanks in advance for any tips.

+8
r
source share
4 answers

Use sweep to work with a specific field of the array: rows are the second dimension (margin).

 sweep(a,MARGIN=2,c(1,5),FUN="-") 
+15
source share
 > library (plyr) > aaply(a, 1, "-", c(1,5) ) , , = 1 X1 1 2 1 0 -2 2 1 -1 , , = 2 X1 1 2 1 4 2 2 5 3 
+4
source share

Use scale to subtract either the average or the specified vector from each row, and then divide it by either the standard deviation or the specified vector.

In your example: scale(a, c(1,5), FALSE)

+3
source share
 > a - rep(c(1,5),each=2) , , 1 [,1] [,2] [1,] 0 -2 [2,] 1 -1 , , 2 [,1] [,2] [1,] 4 2 [2,] 5 3 
+1
source share

All Articles