How to repeat column values in R matrix by values in another column?

R ProgrammingServer Side ProgrammingProgramming

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
raja
Published on 08-Nov-2021 10:29:30
Advertisements