Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat the values of a row in matrix N number of times

Tags:

r

matrix

If I have a matrix in R that looks like the below:

1,3
7,1
8,2

How would I write code that creates a matrix like this:

1,3
1,3
1,3
7,1
8,2
8,2

Where it repeats the row based on the right .column value? Keep in mind I have a matrix that actually has a lot more rows than 2

like image 1000
user2120963 Avatar asked Nov 30 '22 13:11

user2120963


2 Answers

# construct your initial matrix
x <- matrix( c( 1 , 3 , 7 , 1 , 8 , 2 ) , 3 , 2 , byrow = TRUE )

# take the numbers 1 thru the number of rows..
1:nrow(x)

# repeat each of those elements this many times
x[ , 2 ]

# and place both of those inside the `rep` function
rows <- rep( 1:nrow(x) , x[ , 2 ] )

# ..then return exactly those rows!
x[ rows , ]

# or save into a new variable
y <- x[ rows , ]
like image 132
Anthony Damico Avatar answered Dec 02 '22 03:12

Anthony Damico


Here is your original matrix:

a<-matrix(c(1,7,8,3,1,2),3,2)

This makes you the first column:

rep(a[,1],times=a[,2])

And this makes you the second column:

rep(a[,2],times=a[,2])

Combine these with cbind:

cbind(rep(a[,1],times=a[,2]),rep(a[,2],times=a[,2]))

     [,1] [,2]
[1,]    1    3
[2,]    1    3
[3,]    1    3
[4,]    7    1
[5,]    8    2
[6,]    8    2
like image 42
Jouni Helske Avatar answered Dec 02 '22 03:12

Jouni Helske