How to add name to data frame columns in R?


A data frame can be created by using data.frame function but in this case R generates the column names using the values we pass for the data. For example, if we pass a probability distribution as shown in the below examples then its name will be there. If we want to change those names then setNames function can be used along with the data frame name.

Example

 Live Demo

df1<-data.frame(rnorm(20),rnorm(20))
df1

Output

     rnorm.20.    rnorm.20..1
1  -0.24431409   1.48414429
2  -0.04429157  -1.07317747
3   1.03638861   1.23016674
4  -1.51950536   1.01723593
5  -1.29030669   1.59741022
6  -0.02540577   0.16847649
7   0.89598486   1.37993236
8  -1.61080153  -0.89799825
9  -0.54181883  -0.53642593
10 -0.21685719  -0.34991237
11 -0.48691372   0.03656945
12  0.61789184  -0.68130916
13  1.11895194  -1.03310011
14  0.46876609  -0.47855369
15  0.94841120  -0.25945237
16 -0.33669202   0.38229316
17 -0.84262751  -0.62787283
18  1.54774271  -1.97730922
19 -0.23887277   0.02692167
20 -0.33640096   0.35218858

Setting names of columns in df1 −

Example

setNames(df1,c("x1","x2"))

Output

      x1            x2
1  -0.24431409   1.48414429
2  -0.04429157  -1.07317747
3   1.03638861   1.23016674
4  -1.51950536   1.01723593
5  -1.29030669   1.59741022
6  -0.02540577   0.16847649
7   0.89598486   1.37993236
8  -1.61080153  -0.89799825
9  -0.54181883  -0.53642593
10 -0.21685719  -0.34991237
11 -0.48691372   0.03656945
12  0.61789184  -0.68130916
13  1.11895194  -1.03310011
14  0.46876609  -0.47855369
15  0.94841120  -0.25945237
16 -0.33669202   0.38229316
17 -0.84262751  -0.62787283
18  1.54774271  -1.97730922
19 -0.23887277   0.02692167
20 -0.33640096   0.35218858

Example

 Live Demo

df2<-data.frame(rpois(20,8),rpois(20,5))
df2

Output

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

Setting names of columns in df2 −

Example

setNames(df2,c("y1","y2"))

Output

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

Updated on: 17-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements