- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to expand a matrix rows by their index position in R?
To expand a matrix rows by its index position in R, we can follow the below steps −
- First of all, create a matrix.
- Then, use rep and seq_len function with nrow to expand the matrix rows by their index position.
Create the matrix
Let’s create a matrix as shown below −
M<-matrix(rnorm(18),nrow=6) M
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [,3] [1,] 1.1504336 -2.7945635 -1.1192209 [2,] 1.8228588 0.5034033 -0.9991265 [3,] 0.7930331 -0.1489556 -0.3942745 [4,] 0.3773271 1.4935511 0.4641247 [5,] 1.2586923 -0.2941518 -0.7457999 [6,] 0.6746511 1.7114469 1.1954979
Expand the matrix
Using rep and seq_len function with nrow to expand the rows in M by their index position −
M<-matrix(rnorm(18),nrow=6) M<-M[rep(seq_len(nrow(M)),1:6),] M
Output
[,1] [,2] [,3] [1,] 1.1504336 -2.7945635 -1.1192209 [2,] 1.8228588 0.5034033 -0.9991265 [3,] 1.8228588 0.5034033 -0.9991265 [4,] 0.7930331 -0.1489556 -0.3942745 [5,] 0.7930331 -0.1489556 -0.3942745 [6,] 0.7930331 -0.1489556 -0.3942745 [7,] 0.3773271 1.4935511 0.4641247 [8,] 0.3773271 1.4935511 0.4641247 [9,] 0.3773271 1.4935511 0.4641247 [10,] 0.3773271 1.4935511 0.4641247 [11,] 1.2586923 -0.2941518 -0.7457999 [12,] 1.2586923 -0.2941518 -0.7457999 [13,] 1.2586923 -0.2941518 -0.7457999 [14,] 1.2586923 -0.2941518 -0.7457999 [15,] 1.2586923 -0.2941518 -0.7457999 [16,] 0.6746511 1.7114469 1.1954979 [17,] 0.6746511 1.7114469 1.1954979 [18,] 0.6746511 1.7114469 1.1954979 [19,] 0.6746511 1.7114469 1.1954979 [20,] 0.6746511 1.7114469 1.1954979 [21,] 0.6746511 1.7114469 1.1954979
- Related Articles
- How to expand a data frame rows by their index position in R?
- How to replicate a matrix by rows in R?
- How to divide matrix rows in R by row median?
- How to combine two rows in R matrix by addition?
- How to divide the matrix rows by row maximum in R?
- How to divide matrix rows by number of columns in R?
- How to divide the matrix rows by row minimum in R?
- How to randomize rows of a matrix in R?
- How to divide the matrix rows by row standard deviation in R?
- How to combine matrix rows alternately in R?
- How to convert matrix rows into a list in R?
- How to create a matrix with equal rows in R?
- How to multiple a matrix rows in R with a vector?
- How to multiply a matrix columns and rows with the same matrix rows and columns in R?
- How to remove multiple columns from matrix in R by using their names?

Advertisements