-
Notifications
You must be signed in to change notification settings - Fork 1
/
2-handling-categorical-data.Rmd
290 lines (195 loc) · 5.33 KB
/
2-handling-categorical-data.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
---
author: "Maciej Beręsewicz"
title: "Handling categorical data in R"
output:
html_notebook:
number_sections: yes
toc: yes
---
# Packages
```{r}
library(tidyverse)
library(forcats)
library(haven)
library(reticulate)
use_python("/usr/local/anaconda3/bin/python")
```
# Settings
R setup
```{r}
knitr::opts_chunk$set(engine.path = list(
python = "/usr/local/anaconda3/bin/python",
julia = "/Applications/Julia-1.3.app/Contents/Resources/julia/bin/"
))
```
# R
## factors / characters
We use `base::factor` function to create factor
```{r}
data <- 1:10
data_f <- as.factor(data)
data_f
```
Using `base::levels` we get levels
```{r}
levels(data_f)
```
Now, create a factor with levels and labels defined
```{r}
f1 <- factor(x = c(1,2,3,1,2,3,-9),
levels = c(1,2,3,-9, 0),
labels = c("Yes", "No", "Don't know", "N/A", "NULL"),
ordered = FALSE)
f1
```
Note that `as.numeric` replaces original data!!! (no -9 values)
```{r}
as.numeric(f1)
```
Function `as.character` converts replaces numbers with labels.
```{r}
as.character(f1)
```
Using table
```{r}
table(f1)
```
To drop levels with 0 observations (not recommended for initial analysis) we can use `table(., exclude = "level")`
```{r}
table(f1, exclude = "NULL")
```
or `base::droplevels` function
```{r}
table(droplevels(f1))
```
or `xtabs(., drop.unused.levels = TRUE)`
```{r}
xtabs(~f1, drop.unused.levels = TRUE)
```
We can change the reference class (i.e. first level) with `relevel` function.
```{r}
relevel(f1, ref = "No")
```
In R we can create an ordered factor (for ordered categorical data).
```{r}
f2 <- factor(x = mtcars$cyl,
levels = c(4, 6, 8),
labels = c("Small", "Medium", "Big"),
ordered = TRUE)
f2
```
Note `<` symbols in `levels`.
## other R packages
### haven
```{r}
x <- labelled(x = c(1, 2, 1, 2, 10, 9), labels = c(Unknown = 9, Refused = 10))
x
```
```{r}
as.numeric(x)
```
```{r}
as_factor(x)
```
### forcats
Main functions
+ `fct_reorder()`: Reordering a factor by another variable.
+ `fct_infreq()`: Reordering a factor by the frequency of values.
+ `fct_relevel()`: Changing the order of a factor by hand.
+ `fct_lump()`: Collapsing the least/most frequent values of a factor into “other”.
Other functions -- https://forcats.tidyverse.org/reference/index.html
```{r}
fct_inorder(f = f2, ordered = F) ## in orde of appearance
```
```{r}
fct_infreq(f = f2, ordered = F) ## by frequency
```
```{r}
fct_count(f2) ## frequency table (result: data.frame)
```
```{r}
fct_lump(f2, n = 1, other_level = "other levels") ## aggregates based frequency
```
```{r}
fct_collapse(f2,
other = c("Big", "Medium"))
```
About missing levels
```{r}
f1 <- factor(c("a", "a", NA, NA, "a", "b", NA, "c", "a", "c", "b"))
table(f1)
f2 <- fct_explicit_na(f1, na_level = "Missing")
table(f2)
```
### Other useful functions
```{r}
cut(1:10, breaks = c(0,5,10), right = T)
```
### Further reading
-- expss -- https://cran.r-project.org/web/packages/expss/vignettes/labels-support.html
# Python
Categorical data can be handled by pandas (https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html).
```{python}
import pandas as pd
import numpy as np
```
## Pandas and categorical data
Create dummy variable `pd.Series` where we define that it is of `category` type.
```{python}
s = pd.Series(["a", "b", "c", "a"], dtype="category")
s
```
If we would like to convert character column to category one we need to use `astype` method. Below we do the following task:
1. create a pandas DataFrame with `pd.DataFrame`
2. Create new column and indicate its type `astype('category')` which is similar with R `as.factor`
```{python}
df = pd.DataFrame({"A": ["a", "b", "c", "a"]})
df["B"] = df["A"].astype('category')
df
```
We can also create numeric variable and convert it to `category`
```{python}
df = pd.DataFrame({"A": np.arange(0,10,1)})
df["B"] = df["A"].astype('category')
df
```
Further, we may use `cut` function which works similarly as the `cut` function in R
```{python}
df["group"] = pd.cut(df.A, [0,5,10], right = True, include_lowest = True, labels = ['0-5','5-10'])
df
```
Finally, there is a function `pd.Categorical` which explicitly creates factor / categorical variable.
```{python}
new_col = pd.Categorical(values= np.repeat([1,2,3], 3), categories=[1,2,3], ordered=True)
new_col
```
# Julia
Julia contains CategoricalArrays package that enables working with factors
```{julia}
using DataFrames
using CategoricalArrays
using FreqTables
```
Let's create a vector of 1,2,3 repeated 3 times which then we can convert to Categorical Array using `CategoricalArray` function from the `CategoricalArrays` package
```{julia}
x = repeat([9,7,3], outer=3)
simple_cat_array = CategoricalArray(x)
```
We may see levels using `levels` function
```{julia}
levels(simple_cat_array)
```
Further, we may change order of levels with new one using `levels!` which indicate mutating in place function
```{julia}
levels!(simple_cat_array, [9,7,3]);
levels(simple_cat_array)
```
Next, we can create DataFrame with categorical variables
```{julia}
df = DataFrame(A = ["A", "B", "C", "D", "D", "A"],
B = ["X", "X", "X", "Y", "Y", "Y"])
```
```{julia}
categorical!(df, :A)
```
Other useful functions can be found http://juliadata.github.io/CategoricalArrays.jl/stable/using.html