开发者

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


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="-")


> 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


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)


> 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜