Home > OS >  Repeat specific rows a given number of times in R
Repeat specific rows a given number of times in R

Time:03-30

I have the matrix

x=matrix(c(1,1,2,2,10,10,20,20,21,21,30,30,31,31,40,40,
           101,103,102,103,111,112,120,121,120,121,130,131,130,131,140,141),16,2)

I want to repeat each two rows of x a given number of times, that is based on y=c(2,2,2,1,1,1,1,1).

I mean that the first two rows of x are repeated two times (y[1] is equal to 2), the next two rows of x are repeated two times (y[2] is equal to 2), and so on. The last two rows of x are repeated once since (y[8] is equal to 1) is equal to one.

I have tried with rep but it repeats each row, but not every two rows.

I do not want to use any package, just base. Also, I want to avoid any for loop.

CodePudding user response:

Using sequence:

s <- rep(seq(nrow(x) / 2), y)
x[sequence(rep(2, length(s)), s*2-1), ]

#       [,1] [,2]
#  [1,]    1  101
#  [2,]    1  103
#  [3,]    1  101
#  [4,]    1  103
#  [5,]    2  102
#  [6,]    2  103
#  [7,]    2  102
#  [8,]    2  103
#  [9,]   10  111
# [10,]   10  112
# [11,]   10  111
# [12,]   10  112
# [13,]   20  120
# [14,]   20  121
# [15,]   21  120
# [16,]   21  121
# [17,]   30  130
# [18,]   30  131
# [19,]   31  130
# [20,]   31  131
# [21,]   40  140
# [22,]   40  141

CodePudding user response:

x=matrix(c(1,1,2,2,10,10,20,20,21,21,30,30,31,31,40,40,
           101,103,102,103,111,112,120,121,120,121,130,131,130,131,140,141),16,2)


s <- rep(seq_len(8),  c(2,2,2,1,1,1,1,1))

x[as.vector(rbind(s*2 -1, s*2)),]

##>
##>      [,1] [,2]
##> [1,]    1  101
##> [2,]    1  103
##> [3,]    1  101
##> [4,]    1  103
##> [5,]    2  102
##> [6,]    2  103
##> [7,]    2  102
##> [8,]    2  103
##> [9,]   10  111
##>[10,]   10  112
##>[11,]   10  111
##>[12,]   10  112
##>[13,]   20  120
##>[14,]   20  121
##>[15,]   21  120
##>[16,]   21  121
##>[17,]   30  130
##>[18,]   30  131
##>[19,]   31  130
##>[20,]   31  131
##>[21,]   40  140
##>[22,]   40  141  
  • Related