How to add a string before each numeric value in an R data frame column?


Sometimes the unique identity column of a data frame is not recorded as intended, it contains only numeric values that does not solve the data characteristic purpose. Therefore, we might want to add a string before those numeric values to make the data more sensible for viewers and analysts. This can be easily done with the help of gsub function.

Consider the below data frame −

Example

 Live Demo

set.seed(111)
x1<-1:20 x2<sample(1:10,20,replace=TRUE)
df1<-data.frame(x1,x2)
df1

Output

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

Adding ID before each value in column x1 of data frame df1 −

Example

df1$x1<-sub("^","ID",df1$x1)
df1

Output

x1 x2
1 ID1 4
2 ID2 3
3 ID3 9
4 ID4 5
5 ID5 3
6 ID6 8
7 ID7 10
8 ID8 1
9 ID9 10
10 ID10 4
11 ID11 8
12 ID12 10
13 ID13 9
14 ID14 8
15 ID15 1
16 ID16 7
17 ID17 5
18 ID18 1
19 ID19 9
20 ID20 8

Let’s have a look at another example −

Example

 Live Demo

Class<-1:20
Score<-sample(36:100,20)
df2<-data.frame(Class,Score)
df2

Output

Class Score
1 1 89
2 2 82
3 3 55
4 4 63
5 5 57
6 6 99
7 7 90
8 8 43
9 9 86
10 10 42
11 11 44
12 12 56
13 13 80
14 14 45
15 15 46
16 16 37
17 17 41
18 18 60
19 19 59
20 20 68

Adding Class before each value in column Class of data frame df2 −

Example

df2$Class<-sub("^","Class ",df2$Class)
df2

Output

Class Score
1 Class 1 60
2 Class 2 70
3 Class 3 42
4 Class 4 87
5 Class 5 71
6 Class 6 63
7 Class 7 73
8 Class 8 100
9 Class 9 97
10 Class 10 39
11 Class 11 66
12 Class 12 41
13 Class 13 65
14 Class 14 40
15 Class 15 72
16 Class 16 89
17 Class 17 96
18 Class 18 76
19 Class 19 95
20 Class 20 77

Updated on: 14-Oct-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements