How to name a data frame column with a vector value that has the same name in R?


To change the column name of a data frame in R, we can use setNames function. For example, if we have a data frame called df that contains column x and we want to change it to value “Ratings” which is stored in a vector called x then we can use the code df<-data.frame(x=sample(1:10,20,replace=TRUE)).

Example

Consider the below data frame:

Live Demo

> x<-"Ratings"
> y<-data.frame(x=sample(1:10,20,replace=TRUE))
> y

Output

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

Changing x in y to Ratings:

Example

> y<-setNames(y,x)
> y

Output

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

Let’s have a look at another example:

Example

Live Demo

> S<-"Salary"
> df_Salary<-data.frame(S=sample(20000:50000,20,replace=TRUE))
> df_Salary

Output

   S
1 31827
2 24697
3 45790
4 45345
5 22294
6 30749
7 37721
8 33535
9 45941
10 24028
11 48927
12 33818
13 49152
14 43334
15 20294
16 29664
17 23358
18 20475
19 39355
20 40386

Changing S in df_Salary to Salary:

Example

> df_Salary<-setNames(df_Salary,S)
> df_Salary

Output

Salary
1 31827
2 24697
3 45790
4 45345
5 22294
6 30749
7 37721
8 33535
9 45941
10 24028
11 48927
12 33818
13 49152
14 43334
15 20294
16 29664
17 23358
18 20475
19 39355
20 40386

Updated on: 19-Nov-2020

387 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements