Lucas Morin
Lucas Morin

Reputation: 398

Difference between R and Python in handling basic arrays operations

I have the following code in Python :

n = 3
m = 2

y = np.random.normal(loc = 0, scale = 1, size = (n, m))
y_diff = np.expand_dims(y, 1) - np.expand_dims(y, 0)

Which I want to translate to R. As I understand it creates a $ n x n x m $ array, with $y_i - y_j$ as values.

I have found a way to translate expand_dims from python to R (see: Translating Python np.expand_dims to R).

And now have the following code in R:

m = 2
n = 3
x = array(rnorm(m*n),c(m,n))

Both following lines appear to work :

expand_dims(x,1)
expand_dims(x,2)

But not :

expand_dims(x,2) - expand_dims(x,1)

that return :

Error in expand_dims(x, 2) - expand_dims(x, 1) : non-conformable arrays

My intuition is that there is a difference in how Python and R handle basic operations on their arrays.

Any idea on how to make it work in R ?

Upvotes: 1

Views: 140

Answers (1)

duckmayr
duckmayr

Reputation: 16930

I think listarrays::expand_dims() is not truly working how you expect it to; I think that's where your issue is. You should be able to see this by comparing

np.expand_dims(y, 1)

with

listarrays::expand_dims(x, 2)

Python's numpy and R both subtract element-wise, so that's not the issue. I think you're better off just manipulating the array directly in R. I will use a simpler n x m matrix for the purposes of exposition

1 2
3 4
5 6

Then in Python we have

z = np.array([[1, 2], [3, 4], [5, 6]])
z

array([[1, 2],
       [3, 4],
       [5, 6]])

np.expand_dims(z, 1) - np.expand_dims(z, 0)

array([[[ 0,  0],
        [-2, -2],
        [-4, -4]],

       [[ 2,  2],
        [ 0,  0],
        [-2, -2]],

       [[ 4,  4],
        [ 2,  2],
        [ 0,  0]]])

and in R

n <- 3
m <- 2
z <- matrix(1:(n*m), nrow = n, byrow = TRUE)
z
#      [,1] [,2]
# [1,]    1    2
# [2,]    3    4
# [3,]    5    6
array(rep(t(z), each = 3), dim = c(n, m, n)) - array(z, dim = c(n, m, n))
# , , 1
# 
#      [,1] [,2]
# [1,]    0    0
# [2,]   -2   -2
# [3,]   -4   -4
# 
# , , 2
# 
#      [,1] [,2]
# [1,]    2    2
# [2,]    0    0
# [3,]   -2   -2
# 
# , , 3
# 
#      [,1] [,2]
# [1,]    4    4
# [2,]    2    2
# [3,]    0    0

Upvotes: 1

Related Questions