R和Python在处理基本数组操作方面的区别 [英] Difference between R and Python in handling basic arrays operations
问题描述
我在Python中具有以下代码:
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)
我想将其转换为R。据我所知,它使用$ y_i创建了一个$ nxnxm $数组- y_j $作为值。
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.
我找到了一种将expand_dims从python转换为R的方法(请参阅:将Python np.expand_dims转换为R )。
I have found a way to translate expand_dims from python to R (see: Translating Python np.expand_dims to R).
现在在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)
但不是:
expand_dims(x,2) - expand_dims(x,1)
返回:
Error in expand_dims(x, 2) - expand_dims(x, 1) : non-conformable arrays
我的直觉是Python和R处理数组基本操作的方式有所不同。
My intuition is that there is a difference in how Python and R handle basic operations on their arrays.
关于如何使其在R中工作的任何想法?
Any idea on how to make it work in R ?
推荐答案
我认为 listarrays :: expand_dims()
不能真正地按照您的预期工作。我认为这就是您的问题所在。您应该可以通过比较
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)
与
listarrays::expand_dims(x, 2)
Python的 numpy
和R都按元素相减,所以这不是问题。我认为您最好直接在R中操作数组。出于说明的目的,我将使用更简单的nxm矩阵
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
然后在Python中我们有了
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]]])
和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
这篇关于R和Python在处理基本数组操作方面的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!