How to create a data frame with a column having repeated values in R?


To create a data frame with a column having repeated values, we simply need to use rep function and we can repeat the values in a sequence of the values passed or repeating each value a particular number of times. For example, if we have three values 1, 2, 3 then the data frame can be created by repeating these values as 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3 or by repeating the same as 1, 1, 1, 2, 2, 2, 3, 3, 3.

Example 1

 Live Demo

x<-rep(c(1,2,3,4),times=5)
df1<-data.frame(x)
df1

Output

   x
1  1
2  2
3  3
4  4
5  1
6  2
7  3
8  4
9  1
10 2
11 3
12 4
13 1
14 2
15 3
16 4
17 1
18 2
19 3
20 4

Example 2

 Live Demo

y<-rep(c(1,2,3,4),each=5)
df2<-data.frame(y)
df2

Output

   y
1  1
2  1
3  1
4  1
5  1
6  2
7  2
8  2
9  2
10 2
11 3
12 3
13 3
14 3
15 3
16 4
17 4
18 4
19 4
20 4

Example 3

 Live Demo

z<-rep(c("A","B","C","D","E"),each=4)
df3<-data.frame(z)
df3

Output

   z
1  A
2  A
3  A
4  A
5  B
6  B
7  B
8  B
9  C
10 C
11 C
12 C
13 D
14 D
15 D
16 D
17 E
18 E
19 E
20 E

Example 4

 Live Demo

w<-rep(c("A","B","C","D","E"),times=4)
df4<-data.frame(w)
df4

Output

   w
1  A
2  B
3  C
4  D
5  E
6  A
7  B
8  C
9  D
10 E
11 A
12 B
13 C
14 D
15 E
16 A
17 B
18 C
19 D
20 E

Updated on: 17-Oct-2020

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements