How to add a prefix to columns of an R data frame?


If we want to provide more information about the data, we have in columns of an R data frames then we might want to use prefixes. These prefixes help everyone to understand the data, for example, we can use data set name as a prefix, the analysis objective as a prefix, or something that is common among all the columns. To add a prefix to columns of an R data frame, we can use paste function to separate the prefix with the original column names.

Example

Consider the below data frame −

Example

set.seed(100)
Rate <-sample(1:100,20)
Level <-sample(1:10,20,replace=TRUE)
Region <-rep(1:4,times=5)
df <-data.frame(Rate,Level,Region)
df

Output

Rate Level Region
1 74 2 1
2 89 3 2
3 78 4 3
4 23 4 4
5 86 4 1
6 70 5 2
7 4 7 3
8 55 9 4
9 95 4 1
10 7 2 2
11 91 6 3
12 93 7 4
13 43 1 1
14 82 6 2
15 61 9 3
16 12 9 4
17 51 9 1
18 72 6 2
19 18 8 3
20 25 7 4

Adding prefix to the columns of the data frame df −

Example

colnames(df) <-paste("2FactorData",colnames(df),sep="-")
df

Output

2FactorData-Rate 2FactorData-Level 2FactorData-Region
1 74 2 1
2 89 3 2
3 78 4 3
4 23 4 4
5 86 4 1
6 70 5 2
7 4 7 3
8 55 9 4
9 95 4 1
10 7 2 2
11 91 6 3
12 93 7 4
13 43 1 1
14 82 6 2
15 61 9 3
16 12 9 4
17 51 9 1
18 72 6 2
19 18 8 3
20 25 7 4

Let’s have a look at another example −

Example

x1 <-1:20
x2 <-20:1
y <-rnorm(20)
df_new <-data.frame(x1,x2,y)
df_new

Output

   x1    x2    y
1 1 20 -0.69001432
2 2 19 -0.22179423
3 3 18 0.18290768
4 4 17 0.41732329
5 5 16 1.06540233
6 6 15 0.97020202
7 7 14 -0.10162924
8 8 13 1.40320349
9 9 12 -1.77677563
10 10 11 0.62286739
11 11 10 -0.52228335
12 12 9 1.32223096
13 13 8 -0.36344033
14 14 7 1.31906574
15 15 6 0.04377907
16 16 5 -1.87865588
17 17 4 -0.44706218
18 18 3 -1.73859795
19 19 2 0.17886485
20 20 1 1.89746570
colnames(df_new) <-paste("MultipleRegression",colnames(df_new),sep="_")
df_new

Output

MultipleRegression_x1 MultipleRegression_x2 MultipleRegression_y
1 1 20 -0.69001432
2 2 19 -0.22179423
3 3 18 0.18290768
4 4 17 0.41732329
5 5 16 1.06540233
6 6 15 0.97020202
7 7 14 -0.10162924
8 8 13 1.40320349
9 9 12 -1.77677563
10 10 11 0.62286739
11 11 10 -0.52228335
12 12 9 1.32223096
13 13 8 -0.36344033
14 14 7 1.31906574
15 15 6 0.04377907
16 16 5 -1.87865588
17 17 4 -0.44706218
18 18 3 -1.73859795
19 19 2 0.17886485
20 20 1 1.89746570

Updated on: 21-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements