Wencheng Lau-Medrano
Wencheng Lau-Medrano

Reputation: 753

Insert a row into an array in R

I have an array of dim c(10, 12, 20, 14, 5) and I want to insert an empty row, so at the end dim should be c(10, 13, 20, 14, 5). Is there any quickly and elegant way to do that (avoiding loops)?

Upvotes: 1

Views: 435

Answers (1)

r2evans
r2evans

Reputation: 160437

I think package abind can help. The trick is creating an array with the same dimensions but replacing the augmenting dim with just 1:

# original array
a <- array(seq.int(2*3*4), dim=c(2, 3, 4))
# slice to be added to the second axis
b <- array(100+seq.int(2*1*4), dim=c(2, 1, 4))

library(abind)
d <- abind(a, b, along=2)
dim(d)
# [1] 2 4 4
d
# , , 1
#      [,1] [,2] [,3] [,4]
# [1,]    1    3    5  101
# [2,]    2    4    6  102
# , , 2
#      [,1] [,2] [,3] [,4]
# [1,]    7    9   11  103
# [2,]    8   10   12  104
# , , 3
#      [,1] [,2] [,3] [,4]
# [1,]   13   15   17  105
# [2,]   14   16   18  106
# , , 4
#      [,1] [,2] [,3] [,4]
# [1,]   19   21   23  107
# [2,]   20   22   24  108

Upvotes: 2

Related Questions