-
Notifications
You must be signed in to change notification settings - Fork 1
/
factor.Rmd
39 lines (29 loc) · 998 Bytes
/
factor.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
## Factors
* A factor is a vector object (1 dimension) used to specify a **discrete classification (grouping)** of the components of other vectors.
* Factors are mainly used for **statistical modeling**, and can also be useful for graphing.
* You can create factors with the **factor** function, for example:
```{r}
e <- factor(c("high", "low", "medium", "low"))
# check the structure of e
str(e)
```
* Example of a character vector versus a factor
```{r}
# factor
e <- factor(c("high", "low", "medium", "low"))
# character vector
e2 <- c("high", "low", "medium", "low")
# Check the structure of both objects
str(e)
str(e2)
```
* Groups in factors are called **levels**.<br>
Levels can be **ordered**. Then, some operations applied on numeric vectors can be used:
```{r, eval=F}
# unordered factor:
e <- factor(c("high", "low", "medium", "low"))
max(e) # throws an error
# ordered factor
e_ord <- factor(e, levels=c("low", "medium", "high"), ordered=TRUE)
max(e_ord) # outputs "high"
```