How to repeat a column of a data frame and join it with another data frame in R by rows?


Suppose we have a data frame df1 that contains 5 columns and another data frame df2 that contains only column but the data type of the columns in both the data frames is same. Now we might want to add the column of the second data frame starting at the end of the rows of the first data frame by creating the same number of columns as in first data frame. This might be required by researchers to understand the impact of an external variable on the result of the analysis and it can be done with the help of sapply function.

Consider the below data frame −

Example

 Live Demo

set.seed(259)
x1<-sample(0:9,20,replace=TRUE)
x2<-sample(1:10,20,replace=TRUE)
x3<-sample(11:20,20,replace=TRUE)
x4<-sample(16:20,20,replace=TRUE)
x5<-sample(41:50,20,replace=TRUE)
df1<-data.frame(x1,x2,x3,x4,x5)
df1

Output

  x1 x2 x3  x4  x5
1 3  2  19  16  41
2 8  3 14 17 47
3 6  10 13 17 50
4 1  10 18 20 50
5 5  5 13 18 49
6 3  10 13 19 48
7 3  8 13 16 48
8 8   1 15 17 49
9 9  6 13 16 50
10 7 5 19 19 43
11 3 10 12 17 42
12 4 5 17 18 47
13 7 9 13 19 48
14 8 5 11 19 41
15 3 1 19 18 50
16 9 2 16 17 41
17 0 5 17 19 42
18 2 7 11 17 42
19 3 1 14 18 41
20 1 2 19 18 47

Example

 Live Demo

x1<-sample(0:50,20)
df2<-data.frame(x1)
df2

Output

x1
1 45
2 25
3 24
4 46
5 32
6 3
7 30
8 6
9 14
10 36
11 1
12 34
13 47
14 9
15 22
16 21
17 16
18 44
19 31
20 26

Joining df2 columns with df1 by repeating the column of df2 to the number of columns in df1 −

Example

data.frame(sapply(df1,c,unlist(df2)),row.names=NULL)

Output

  x1 x2 x3 x4 x5
1 9  4  12 16 48
2 2  9  16 19 47
3 6  7  17 17 46
4 1  8  17 16 44
5 3  8  12 18 44
6 4  8  16 20 42
7 6  3  13 17 41
8 0  3  18 18 43
9 8  9  11 17 46
10 4 9  14 16 44
11 2 3  20 18 44
12 9 3  11 20 45
13 4 1  12 17 42
14 6 8  11 17 47
15 3 8  20 18 47
16 8 8  12 20 43
17 5 4  18 18 48
18 4 4  15 16 43
19 9 7  11 17 50
20 2  7  11 20 44
21 34  34 34 34 34
22 8 8  8 8 8
23 30  30 30 30 30
24 6 6 6 6 6
25 12 12 12 12 12
26 7 7 7 7 7
27 36 36 36 36 36
28 31 31 31 31 31
29 44 44 44 44 44
30 24 24 24 24 24
31 26 26 26 26 26
32 22 22 22 22 22
33 14 14 14 14 14
34 2 2 2 2 2 35
33 33 33 33 33
36 9 9 9 9 9
37 15 15 15 15 15
38 11 11 11 11 11
39 19 19 19 19 19
40 32 32 32 32 32

Updated on: 16-Oct-2020

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements