How to repeat column values in R data frame by values in another column?


To repeat column values in R data frame by values in another column, we can follow the below steps −

  • First of all, create a data frame.

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

Example

Create the data frame

Let’s create a data frame as shown below −

x<-1:10
y<-sample(1:5,10,replace=TRUE)
df<-data.frame(x,y)
df

Output

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

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

Repeat a column values by values in another column

Using rep function along with cbind function to repeat column x values in the data frame df by values in column y −

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

Output

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

Updated on: 11-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements