How can I subtract a vector of each row in a 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
What I am trying to get is:
, , 1
[,1] [,2]
[1,] 0 -2
[2,] 1 -1
, , 2
[,1] [,2]
[1,] 4 2
[2,] 5 3
Thanks in advance for any hints
Use
sweepto operate on a particular margin of the array: rows are the second dimension (margin).