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
# 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 , ]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With