pythonrnumpymatrix

Define a matrix in R in a similar fashon as with Numpy


I love the fact that using numpy in Python it is very easy to define a matrix/array in a way that is very close to the mathematical definition. Does R have a similar way of achieving this result?

import numpy as np

n = np.arange(4)    
m = np.arange(6)

## Now I will define the matrix N_mat[i,j]=m[i]*n[j] with 6 rows
## and 4 columns
N_mat = m[:,np.newaxis]*n[np.newaxis,:]

Solution

  • Probably you are looking for outer

    n <- seq_len(4) - 1
    m <- seq_len(6) - 1
    N_mat <- outer(m, n)
    

    where

    > N_mat
         [,1] [,2] [,3] [,4]
    [1,]    0    0    0    0
    [2,]    0    1    2    3
    [3,]    0    2    4    6
    [4,]    0    3    6    9
    [5,]    0    4    8   12
    [6,]    0    5   10   15