user1234440
user1234440

Reputation: 23567

R replicate elements based on its index

Given a matrix,

x<-matrix(rnorm(4))

How can I do the following

So row 1's element will get replicated by 1 time, row 2's element by 2 times, etc...

I tried to do it with 'rep' and loop but its really slow if the matrix is large.

Upvotes: 1

Views: 436

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59980

If you just want one long vector then given the rep is vectorised you can simply do...

rep( x , times = 1:nrow(x) )
#[1]  1.5921465  0.9901053  0.9901053  0.2125433  0.2125433  0.2125433 -0.9288893 -0.9288893 -0.9288893 -0.9288893

If you need each row as a seperate element try lapply, a different kind of looping construct...

lapply( 1:nrow(x) , function(i) rep( x[i,] , times = i ) )
#[[1]]
#[1] 1.592147

#[[2]]
#[1] 0.9901053 0.9901053

#[[3]]
#[1] 0.2125433 0.2125433 0.2125433

#[[4]]
#[1] -0.9288893 -0.9288893 -0.9288893 -0.9288893

This answer assumes that the matrix x is available in your .GlobalEnvironment

Upvotes: 4

Related Questions