Syntax error How to add suffix to column names in R?

How to add suffix to column names in R?



To add suffix to column names in R, we can use paste function. For example, if we have a data frame called df that contains three columns say x, y, and z and we want to add a suffix to these columns say underscore1 (_1) then it can be done by using the command

colnames(df)<-paste(colnames(df),"1",sep="_")

Example1

Consider the below data frame −

Live Demo

> x<-rpois(20,5)
> y<-rpois(20,5)
> z<-rpois(20,5)
> df1<-data.frame(x,y,z)
> df1

Output

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

Adding suffix _1 to column names in df1 −

> colnames(df1)<-paste(colnames(df1),"1",sep="_")
> df1

Output

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

Example2

Live Demo

> First<-rnorm(20)
> Second<-rnorm(20)
> df2<-data.frame(First,Second)
> df2

Output

         First     Second
1   1.00282455  0.5759739
2   0.35202536  1.3904835
3   0.41651858 -1.4070300
4  -1.07936487  1.0501346
5  -0.48215611 -0.9315004
6   0.01836988  0.4579780
7  -0.53021884 -0.9794603
8   0.07023623 -0.9540754
9  -0.82364958 -1.5772256
10 -0.41617725  0.5206476
11  0.18096607 -0.2642566
12  0.09188606 -1.1760547
13 -0.17121381 -1.7566332
14 -1.71346331 -0.1962034
15 -0.01604117 -1.2129497
16  0.16550767 -0.6901972
17  1.19758517 -1.3377314
18 -0.19054988  1.1551758
19  0.23210609 -0.8034687
20  1.17883619 -0.8621083

Adding suffix _Group to column names in df2 −

> colnames(df2)<-paste(colnames(df2),"Group",sep="_")
> df2

Output

   First_Group Second_Group
1   1.00282455    0.5759739
2   0.35202536    1.3904835
3   0.41651858   -1.4070300
4  -1.07936487    1.0501346
5  -0.48215611   -0.9315004
6   0.01836988    0.4579780
7  -0.53021884   -0.9794603
8   0.07023623   -0.9540754
9  -0.82364958   -1.5772256
10 -0.41617725    0.5206476
11  0.18096607   -0.2642566
12  0.09188606   -1.1760547
13 -0.17121381   -1.7566332
14 -1.71346331   -0.1962034
15 -0.01604117   -1.2129497
16  0.16550767   -0.6901972
17  1.19758517   -1.3377314
18 -0.19054988    1.1551758
19  0.23210609   -0.8034687
20  1.17883619   -0.8621083
Updated on: 2021-03-05T07:12:54+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements