johannes
johannes

Reputation: 14433

Array: subtract by row

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

Upvotes: 8

Views: 12829

Answers (4)

user2443147
user2443147

Reputation:

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

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

Upvotes: 3

IRTFM
IRTFM

Reputation: 263362

> 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

Upvotes: 4

Ben Bolker
Ben Bolker

Reputation: 226192

Use sweep to operate on a particular margin of the array: rows are the second dimension (margin).

sweep(a,MARGIN=2,c(1,5),FUN="-")

Upvotes: 16

NPE
NPE

Reputation: 500367

> 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

Upvotes: 1

Related Questions