How to add a new column at the front of an existing R data frame?


Generally, when we add a new column to an existing R data frame that column is added at the end of the columns but we might need it at the front. This totally depends on our ease of use, familiarity with variables, and their need. We can add a new column at the front of an existing R data frame by using cbind function.

Example

Consider the below data frame −

ID <-1:20
Class <-rep(c("A","B","C","D"),times=5)
df1 <-data.frame(ID,Class)
df1

Output

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

Now suppose that we want to add a new column Score at the front of the data frame, then it can be done as shown below −

Example

Score <-sample(1:100,20)
df1 <-cbind(Score,df1)
df1

Output

Score ID Class
1 87 1 A
2 99 2 B
3 90 3 C
4 13 4 D
5 100 5 A
6 50 6 B
7 51 7 C
8 89 8 D
9 70 9 A
10 72 10 B
11 36 11 C
12 12 12 D
13 98 13 A
14 93 14 B
15 86 15 C
16 2 16 D
17 35 17 A
18 34 18 B
19 67 19 C
20 44 20 D

Let’s have a look at another example −

Example

x1<-rnorm(20)
x2<-rnorm(20,1)
x3<-rnorm(20,5)
df2<-data.frame(x1,x2,x3)
df2

Output

      x1       x2       x3
1 -0.78695273 -0.16032953 7.353717
2 0.42981155 1.43909343 3.984902
3 -0.37641622 1.20485374 5.290978
4 -1.21622907 0.30081866 6.565326
5 1.02927851 0.07337432 4.152882
6 0.43039700 -0.01348238 6.327660
7 -1.24557402 1.60498706 5.477046
8 -0.60272849 2.73440013 5.185251
9 0.66006939 0.65014947 5.253295
10 2.05074953 2.19918551 7.592227
11 0.49080818 2.02390100 6.074347
12 -1.73147942 0.95372485 3.403098
13 0.71088366 2.38650843 4.912411
14 0.01382291 -1.19527272 5.360768
15 -1.40104160 0.87244309 4.120040
16 1.25912367 -0.31699684 1.676665
17 -0.12747752 -0.42693514 4.532485
18 -0.72938651 1.87944163 5.431540
19 -1.21136136 1.39399158 4.396011
20 0.59961974 1.68892548 5.674447

Example

y<-rpois(20,2)
df2<-cbind(y,df2)
df2

Output

   y       x1       x2       x3
1 3 -0.78695273 -0.16032953 7.353717
2 2 0.42981155 1.43909343 3.984902
3 1 -0.37641622 1.20485374 5.290978
4 4 -1.21622907 0.30081866 6.565326
5 2 1.02927851 0.07337432 4.152882
6 1 0.43039700 -0.01348238 6.327660
7 3 -1.24557402 1.60498706 5.477046
8 1 -0.60272849 2.73440013 5.185251
9 2 0.66006939 0.65014947 5.253295
10 4 2.05074953 2.19918551 7.592227
11 5 0.49080818 2.02390100 6.074347
12 0 -1.73147942 0.95372485 3.403098
13 1 0.71088366 2.38650843 4.912411
14 3 0.01382291 -1.19527272 5.360768
15 2 -1.40104160 0.87244309 4.120040
16 1 1.25912367 -0.31699684 1.676665
17 3 -0.12747752 -0.42693514 4.532485
18 3 -0.72938651 1.87944163 5.431540
19 2 -1.21136136 1.39399158 4.396011
20 2 0.59961974 1.68892548 5.674447

Updated on: 21-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements