- 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 repeat column values in R matrix by values in another column?
To repeat column values in R matrix by values in another column, we can follow the below steps −
First of all, create a matrix.
Then, use rep function along with cbind function to repeat column values in the matrix by values in another column.
Example
Create the matrix
Let’s create a matrix as shown below −
x<-1:10 y<-sample(1:5,10,replace=TRUE) M<-matrix(c(x,y),ncol=2) M
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [1,] 1 2 [2,] 2 2 [3,] 3 2 [4,] 4 5 [5,] 5 3 [6,] 6 3 [7,] 7 1 [8,] 8 2 [9,] 9 2 [10,] 10 3
Repeat a column values by values in another column
Using rep function along with cbind function to repeat column 1 values in the matrix M by values in column 2 −
x<-1:10 y<-sample(1:5,10,replace=TRUE) M<-matrix(c(x,y),ncol=2) cbind(rep(M[,1],times=M[,2]),rep(M[,2],times=M[,2]))
Output
[,1] [,2] [1,] 1 2 [2,] 1 2 [3,] 2 2 [4,] 2 2 [5,] 3 2 [6,] 3 2 [7,] 4 5 [8,] 4 5 [9,] 4 5 [10,] 4 5 [11,] 4 5 [12,] 5 3 [13,] 5 3 [14,] 5 3 [15,] 6 3 [16,] 6 3 [17,] 6 3 [18,] 7 1 [19,] 8 2 [20,] 8 2 [21,] 9 2 [22,] 9 2 [23,] 10 3 [24,] 10 3 [25,] 10 3
- Related Articles
- How to repeat column values in R data frame by values in another column?
- How to repeat column values of a data.table object in R by number of values in another column?
- How to identify duplicate values in a column of matrix in R?
- How to convert a column values to column names in R?
- How to find the sum of a column values up to a value in another column in R?
- Find the sum of a column values based on another numerical column in R.
- How to subset a matrix based on values in a particular column in R?
- How to check if an R matrix column contains only duplicate values?
- How to subtract column values from column means in R data frame?
- How to repeat the values stored in a data column of MySQL table?
- How to minus one column from another in an R matrix?
- Replace numerical column values based on character column values in R data frame.
- MySQL query to group by column and display the sum of similar values in another column
- How to find the column means of a column based on another column values that represent factor in an R data frame?
- How to select a column of a matrix by column name in R?

Advertisements