R factor Function


R factors variable is a vector of categorical data. factor() function creates a factor variable, and calculates the categorical distribution of a vector data.

factor(x = character(), levels, labels = levels,
exclude = NA, ordered = is.ordered(x))


x: a vector of data
...

> v <- c(1,3,5,8,2,1,3,5,3,5)
> is.factor(v)

[1] FALSE


Calculates the categorical distribution:

> x <- factor(v)
> x

[1] 1 3 5 8 2 1 3 5 3 5
Levels: 1 2 3 5 8


> is.factor(x)

[1] TRUE


Select levels:

> x <- factor(v, levels=c(2,1))
> x

[1] 1 <NA> <NA> <NA> 2 1 <NA> <NA> <NA> <NA>
Levels: 2 1


Change the level value:

> levels(x) <- c("two","one")
> x

[1] one <NA> <NA> <NA> two one <NA> <NA> <NA> <NA>
Levels: two one