# How to add a column between columns or after last column in an R data frame?

Since no one is perfect, people might forget to add all columns that are necessary for the analysis but this problem can be solved. If a column is missing in our data frame and we came to know about it later then it can be added easily with the help of reordering the columns.

## Example

Consider the below data frame −

> x1<-1:20
> x2<-letters[1:20]
> x3<-rep(c(1,2),times=10)
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1   1 a 1
2   2 b 2
3   3 c 1
4   4 d 2
5   5 e 1
6   6 f 2
7   7 g 1
8   8 h 2
9   9 i 1
10 10 j 2
11 11 k 1
12 12 l 2
13 13 m 1
14 14 n 2
15 15 o 1
16 16 p 2
17 17 q 1
18 18 r 2
19 19 s 1
20 20 t 2

Let’s say a column y1 is missing that needs to be in between x1 and x2 then it can be created and added as shown below −

> df$y1<-rep(c(22,24,26,28),times=5) > df<-df[,c("x1","y1","x2","x3")] > df x1 y1 x2 x3 1 1 22 a 1 2 2 24 b 2 3 3 26 c 1 4 4 28 d 2 5 5 22 e 1 6 6 24 f 2 7 7 26 g 1 8 8 28 h 2 9 9 22 i 1 10 10 24 j 2 11 11 26 k 1 12 12 28 l 2 13 13 22 m 1 14 14 24 n 2 15 15 26 o 1 16 16 28 p 2 17 17 22 q 1 18 18 24 r 2 19 19 26 s 1 20 20 28 t 2 Suppose another column is missing which should be in the last position then it can be created and added as follows − > df$y2<-rep(c(100,105,110,115,120),times=4)
> df<-df[,c("x1","y1","x2","x3","y2")]
> df
x1 y1  x2  x3  y2
1   1 22  a  1  100
2   2 24  b  2  105
3   3 26  c  1  110
4   4 28  d  2  115
5   5 22  e  1  120
6   6 24  f  2  100
7   7 26  g  1  105
8   8 28  h  2  110
9   9 22  i  1  115
10 10 24  j  2  120
11 11 26  k  1  100
12 12 28  l  2  105
13 13 22  m  1  110
14 14 24  n  2  115
15 15 26  o  1  120
16 16 28  p  2  100
17 17 22  q  1  105
18 18 24  r  2  110
19 19 26  s  1  115
20 20 28  t  2  120

Updated on: 10-Aug-2020

153 Views