+5 votes
in Programming Languages by (40.5k points)
I want to rename some columns of an R dataframe. Which R function should I use?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

To rename the column(s) of a dataframe, you can use the rename() function of the library dplyr. The rename() function takes dataframe as argument followed by newname = oldname. If you want to rename multiple columns, you can use the following syntax:

df <- rename(df, c(newname1=oldname1, newname2=oldname2,...))

Here is an example to show how to use this function.

To rename one column:

> library(dplyr)
> x <- c(1:10)
> y <-sin(x)
> df <-data.frame(xvals=x, yvals=y)
> df
   xvals      yvals
1      1  0.8414710
2      2  0.9092974
3      3  0.1411200
4      4 -0.7568025
5      5 -0.9589243
6      6 -0.2794155
7      7  0.6569866
8      8  0.9893582
9      9  0.4121185
10    10 -0.5440211
> df <- rename(df, domain=xvals)
> df
   domain      yvals
1       1  0.8414710
2       2  0.9092974
3       3  0.1411200
4       4 -0.7568025
5       5 -0.9589243
6       6 -0.2794155
7       7  0.6569866
8       8  0.9893582
9       9  0.4121185
10     10 -0.5440211

To rename multiple columns:

> library(dplyr)
> x <- c(1:10)
> y <-sin(x)
> df <-data.frame(xvals=x, yvals=y)
> df
   xvals      yvals
1      1  0.8414710
2      2  0.9092974
3      3  0.1411200
4      4 -0.7568025
5      5 -0.9589243
6      6 -0.2794155
7      7  0.6569866
8      8  0.9893582
9      9  0.4121185
10    10 -0.5440211
> df <- rename(df, c(domain=xvals, range=yvals)) # to rename >1 columns
> df
   domain      range
1       1  0.8414710
2       2  0.9092974
3       3  0.1411200
4       4 -0.7568025
5       5 -0.9589243
6       6 -0.2794155
7       7  0.6569866
8       8  0.9893582
9       9  0.4121185
10     10 -0.5440211

Related questions

+5 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer

...