How to associate a character to numbers in an R data frame column?


Sometimes a variable has a character associated with the numerical values such as variable name etc. If we want to associate a character to numbers then paste0 function can be used.

For example, if we have a data frame called df that contains a column say X then we can associate X to each value in the column by using the command given below −

df$X<-paste0(df$X,"X")

Example 1

Following snippet creates a sample data frame −

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

Output

The following dataframe is created −

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

In order to associate x to each value in column x of df1, add the following code to the above snippet −

x<-rpois(20,5)
df1<-data.frame(x)
df1$x<-paste0(df1$x,"x")
df1

Output

If you execute all the above given codes as a single program, it generates the following output −

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

Example 2

Following snippet creates a sample data frame −

y<-rnorm(20)
df2<-data.frame(y)
df2

Output

The following dataframe is created −

        y
1   0.40201269
2   1.45442817
3   0.19279869
4   0.01741902
5   0.12640511
6  -0.63145311
7   1.17144098
8   0.04921049
9  -0.27264455
10 -0.06296358
11 -0.55946672
12 -0.87499521
13  0.63149416
14 -0.27635347
15  1.91809752
16  0.80269915
17 -0.95289964
18 -2.12660318
19 -0.24725334
20  1.17233733

In order to associate y to each value in column y of df2, add the following code to the above snippet −

y<-rnorm(20)
df2<-data.frame(y)
df2$y<-paste0(df2$y,"x")
df2

Output

If you execute all the above given codes as a single program, it generates the following output −

         y
1   0.402012693960396x
2   1.45442816742435x
3   0.192798694532632x
4   0.0174190176140634x
5   0.126405112873785x
6  -0.631453113767031x
7   1.17144097763347x
8   0.0492104895444209x
9  -0.272644548609489x
10 -0.0629635834527344x
11 -0.559466715629088x
12 -0.874995212053932x
13  0.631494159936445x
14 -0.276353468822519x
15  1.91809751953821x
16  0.802699152112939x
17 -0.952899639827688x
18 -2.12660317755088x
19 -0.247253340301469x
20  1.17233733460474x

Updated on: 06-Nov-2021

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements