Akira
Akira

Reputation: 273

Increase one more dimension of the vector or matrix in R

In Python, we have a function called np.newaxis, which increase one more dimension of the original array. I am just wondering if there are any same functionality in R. For example it will return row vector or column vector if I have a plain vector.

I am trying to convert the Python code into R, here is an example:

delta_weights_i_h += hidden_error_term * X[:,None]
delta_weights_h_o += output_error_term * hidden_outputs[:,None]

I don't really know how to convert X[:, None] into R

Thanks for any help !

Upvotes: 2

Views: 4438

Answers (1)

Katia
Katia

Reputation: 3914

If X is a vector, then you can add a dimension using dim() and length() functions

X <- 1:5
X
##[1] 1 2 3 4 5

dim(X) <- c(length(X), 1)
X
##     [,1]
##[1,]    1
##[2,]    2
##[3,]    3
##[4,]    4
##[5,]    5

If X is a matrix or an array with more than 2 dimensions and you want to add axis to be the second dimension:

X <- matrix(1:6, ncol=2)
X
##     [,1] [,2]
##[1,]    1    4
##[2,]    2    5
##[3,]    3    6

dim(X) <- c(dim(X)[1], 1, dim(X)[-1])
dim (X)
##[1] 3 1 2


X
#, , 1
#
#     [,1]
#[1,]    1
#[2,]    2
#[3,]    3
#
#, , 2
#
#     [,1]
#[1,]    4
#[2,]    5
#[3,]    6

Upvotes: 5

Related Questions