How to convert numeric columns to factor using dplyr package in R?

R ProgrammingServer Side ProgrammingProgramming

If we have a numeric column in an R data frame and the unique number of values in the column is low that means the numerical column can be treated as a factor. Therefore, we can convert numeric columns to factor. To do this using dplyr package, we can use mutate_if function of dplyr package.

Loading dplyr package and converting numerical columns in BOD data set (available in base R) to factor columns −

Example

library(dplyr)
str(BOD)
'data.frame': 6 obs. of 2 variables:
$ Time : num 1 2 3 4 5 7
$ demand: num 8.3 10.3 19 16 15.6 19.8
- attr(*, "reference")= chr "A1.4, p. 270"
BOD%>%mutate_if(is.numeric,as.factor)

Output

  Time demand
1  1   8.3
2  2   10.3
3  3   19
4  4   16
5  5   15.6
6  7   19.8

Converting numerical columns in Formaldehyde data set (available in base R) to factor columns −

Example

str(Formaldehyde)
'data.frame': 6 obs. of 2 variables:
$ carb : num 0.1 0.3 0.5 0.6 0.7 0.9
$ optden: num 0.086 0.269 0.446 0.538 0.626 0.782
Formaldehyde%>%mutate_if(is.numeric,as.factor)

Output

   carb  optden
1  0.1   0.086
2  0.3   0.269
3  0.5   0.446
4  0.6   0.538
5  0.7   0.626
6  0.9   0.782

Converting numerical columns in InsectSprays data set (available in base R) to factor columns −

Example

str(InsectSprays)
'data.frame': 72 obs. of 2 variables:
$ count: num 10 7 20 14 14 12 10 23 17 20 ...
$ spray: Factor w/ 6 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...
InsectSprays%>%mutate_if(is.numeric,as.factor)

Output

   count spray
1  10    A
2  7     A
3  20    A
4  14    A
5  14    A
6  12    A
7  10    A
8  23    A
9  17    A
10 20    A
11 14    A
12 13    A
13 11    B
14 17    B
15 21    B
16 11    B
17 16    B
18 14    B
19 17    B
20 17    B
21 19    B
22 21    B
23 7     B
24 13    B
25 0     C
26 1     C
27 7     C
28 2     C
29 3     C
30 1     C
31 2     C
32 1     C
33 3     C
34 0     C
35 1     C
36 4     C
37 3     D
38 5     D
39 12    D
40 6     D
41 4     D
42 3     D
43 5     D
44 5     D
45 5     D
46 5     D
47 2     D
48 4     D
49 3     E
50 5     E
51 3     E
52 5     E
53 3     E
54 6     E
55 1     E
56 1     E
57 3     E
58 2     E
59 6     E
60 4     E
61 11    F
62 9     F
63 15    F
64 22    F
65 15    F
66 16    F
67 13    F
68 10    F
69 26    F
70 26    F
71 24    F
72 13    F
raja
Published on 11-Feb-2021 11:35:46
Advertisements