How to convert factor levels into character in R?


To convert factor levels into character then we can use as.character function by accessing the column of the data frame that contain factor values. For example, if we have a data frame df which contains a factor column named as Gender then this column can be converted into character column as as.character(df$Gender).

Example

 Live Demo

Consider the below data frame −

set.seed(121)
x1<−as.factor(sample(LETTERS[1:5],20,replace=TRUE))
x2<−rnorm(20,1,0.4)
df1<−data.frame(x1,x2)
df1

Output

   x1   x2
1  D 0.7827428
2  D 0.5519596
3  D 0.3852095
4  D 0.3349047
5  A 1.1618117
6  C 0.4082440
7  A 1.5988801
8  C 0.9368104
9  C 1.0383650
10 E 0.2883935
11 D 0.3859827
12 E 1.5254714
13 D 1.2963078
14 A 0.2446046
15 E 0.4702711
16 B 1.1655974
17 B 0.9342977
18 C 0.9110071
19 A 1.3317495
20 B 1.6616840

Example

str(df1)

Output

'data.frame': 20 obs. of 2 variables:
$ x1: Factor w/ 5 levels "A","B","C","D",..: 4 4 4 4 1 3 1 3 3 5 ...
$ x2: num 0.783 0.552 0.385 0.335 1.162 ...

Converting x1 to character column −

df1$x1<−as.character(df1$x1)
str(df1)

Output

'data.frame': 20 obs. of 2 variables:
$ x1: chr "D" "D" "D" "D" ...
$ x2: num 0.783 0.552 0.385 0.335 1.162 ...

Let’s have a look at another example −

Example

 Live Demo

y1<−as.factor(sample(c("India","Canada","Russia"),20,replace=TRUE))
y2<−rpois(20,3)
df2<−data.frame(y1,y2)
df2

Output

    y1   y2
1 Russia  4
2 Canada  1
3 India   5
4 India   3
5 India   3
6 Canada  3
7 Canada  1
8 Canada  1
9 Canada  0
10 India  4
11 Canada 4
12 Canada 5
13 Canada 3
14 India  3
15 Russia 4
16 India  4
17 Canada 3
18 Russia 7
19 India  2
20 Canada 3

Example

str(df2)

Output

'data.frame': 20 obs. of 2 variables:
$ y1: Factor w/ 3 levels "Canada","India",..: 3 1 2 2 2 1 1 1 1 2 ...
$ y2: int 4 1 5 3 3 3 1 1 0 4 ...

Converting y1 to character column −

df2$y1<−as.character(df2$y1)
str(df2)

Output

'data.frame': 20 obs. of 2 variables:
$ y1: chr "Russia" "Canada" "India" "India" ...
$ y2: int 4 1 5 3 3 3 1 1 0 4 ...

Updated on: 17-Oct-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements