Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array: subtract by row

Tags:

r

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

like image 988
johannes Avatar asked May 31 '11 13:05

johannes


People also ask

How do you subtract from a NumPy array?

The most straightforward way to subtract two matrices in NumPy is by using the - operator, which is the simplification of the np. subtract() method - NumPy specific method designed for subtracting arrays and other array-like objects such as matrices.

How do you subtract an array in Java?

Find the minimum non-zero element in the array, print it and then subtract this number from all the non-zero elements of the array. If all the elements of the array are < 0, just print 0.

How do you subtract one array from another array in Python?

subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array. arr2 : [array_like or scalar]2nd Input array.


1 Answers

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="-")
like image 132
Ben Bolker Avatar answered Sep 26 '22 14:09

Ben Bolker