【问题标题】:Difference between R and Python in handling basic arrays operationsR 和 Python 在处理基本数组操作方面的区别
【发布时间】:2020-04-28 13:47:05
【问题描述】:

我在 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。据我了解,它创建了一个 $ n x n x m $ 数组,其中 $y_i - y_j$ 作为值。

我找到了一种将 expand_dims 从 python 转换为 R 的方法(请参阅:Translating Python np.expand_dims to R)。

现在在 R 中有以下代码:

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

以下两行似乎都有效:

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 处理其数组的基本操作的方式有所不同。

关于如何使其在 R 中工作的任何想法?

【问题讨论】:

    标签: python r arrays


    【解决方案1】:

    我认为listarrays::expand_dims() 并没有真正按您的预期工作;我认为这就是你的问题所在。你应该可以通过比较看到这一点

    np.expand_dims(y, 1)
    

    listarrays::expand_dims(x, 2)
    

    Python 的 numpy 和 R 都按元素减去,所以这不是问题。我认为你最好直接在 R 中操作数组。我将使用一个更简单的 n x m 矩阵来说明

    1 2
    3 4
    5 6
    

    然后在 Python 中我们有

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多