Matt
Matt

Reputation: 14541

R equivlent of python numpy slice: [:, None, :]

Given a 2x2 matrix a, convert it into a 2x1 array b where each column is a row vector from a. This is really easy to do in python. Is there an elegant and consise way to do this in R?

> a = np.array([[1, 2], [3, 4]])

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

> b = a[:, None, :]

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

In R I want this input:

a = matrix(1:4, ncol=2, byrow = T)

     [,1] [,2]
[1,]    1    2
[2,]    3    4

to be modified to match this output:

b = array(1:4, dim=c(2,1,2))

, , 1

     [,1]
[1,]    1
[2,]    2

, , 2

     [,1]
[1,]    3
[2,]    4

Upvotes: 1

Views: 226

Answers (1)

doicomehereoften1
doicomehereoften1

Reputation: 567

It seems like you might actually be trying to get a 2x1x2 array? So in R you'd convert the matrix to an array (these are separate classes), specifying your intended dimensions for the new array.

a <- matrix(c(1,2,3,4), 2, byrow=TRUE)
b <- array(t(a), dim=c(2,1,2))
b

Upvotes: 2

Related Questions