Skip to content

Instantly share code, notes, and snippets.

@johnmyleswhite
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmyleswhite/2d5d3905a156ae7331d2 to your computer and use it in GitHub Desktop.
Save johnmyleswhite/2d5d3905a156ae7331d2 to your computer and use it in GitHub Desktop.
Factors expose way too much of their implementation
> x <- c(4, 1, 3, 5, 2)
> # Sorts levels automatically
> f1 <- factor(x)
> f1
[1] 4 1 3 5 2
Levels: 1 2 3 4 5
> # Does not sort levels automatically
> f2 <- factor(x, levels = c(3, 4, 5, 2, 1))
> f2
[1] 4 1 3 5 2
Levels: 3 4 5 2 1
> # But note that the order of the levels shouldn't be important
> is.ordered(f1)
[1] FALSE
> is.ordered(f2)
[1] FALSE
> # Except the order can still determine the correctness of downstream computations
> levels(f1) <- c(5, 4, 3, 2, 1)
> f1
[1] 2 5 3 1 4
Levels: 5 4 3 2 1
> levels(f2) <- c(5, 4, 3, 2, 1)
> f2
[1] 4 1 5 3 2
Levels: 5 4 3 2 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment