How to repeat column values of a data.table object in R by number of values in another column?


To repeat column values of a data.table object by values in another column, we can follow the below steps −

  • First of all, create a data.table object.

  • Then, use rep function along with cbind function to repeat column values in the matrix by values in another column.

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
x<-1:10
y<-sample(1:5,10,replace=TRUE)
DT<-data.table(x,y)
DT

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

     x y
1:   1 2
2:   2 4
3:   3 1
4:   4 5
5:   5 3
6:   6 4
7:   7 2
8:   8 5
9:   9 1
10: 10 1

Repeat a column values by values in another column

Using rep function along with cbind function to repeat column x values in the data.table object DT by values in column y −

library(data.table)
x<-1:10
y<-sample(1:5,10,replace=TRUE)
DT<-data.table(x,y)
cbind(rep(DT$x,times=DT$y),rep(DT$y,times=DT$y))

Output

     [,1] [,2]
[1,]   1   2
[2,]   1   2
[3,]   2   4
[4,]   2   4
[5,]   2   4
[6,]   2   4
[7,]   3   1
[8,]   4   5
[9,]   4   5
[10,]  4   5
[11,]  4   5
[12,]  4   5
[13,]  5   3
[14,]  5   3
[15,]  5   3
[16,]  6   4
[17,]  6   4
[18,]  6   4
[19,]  6   4
[20,]  7   2
[21,]  7   2
[22,]  8   5
[23,]  8   5
[24,]  8   5
[25,]  8   5
[26,]  8   5
[27,]  9   1
[28,] 10   1

Updated on: 11-Nov-2021

409 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements