0

I want to keep a order after change big mark in numbers cut. The reproducible examples:

require(dplyr)
data <- c(rnorm(25, 2000, 500), 19, 10)
data <- data %>% cut(., breaks = 5, dig.lab = 4)
levels(data)

Results:

"(7.265,557]" "(557,1104]"  "(1104,1651]" "(1651,2198]" "(2198,2748]"

When I change the format:

nd_data <- data %>% prettyNum(big.mark = ".")  %>% as.factor()
levels(nd_data)
"(1.104,1.651]" "(1.651,2.198]" "(2.198,2.748]" "  (557,1.104]" "  (7.265,557]"

The order change. How to keep, without a manual change, because I have different data sets?

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • Possible duplicate of [Reformarring complex factor vector with comma separation after thousnad](https://stackoverflow.com/questions/34608324/reformarring-complex-factor-vector-with-comma-separation-after-thousnad) – camille Mar 12 '19 at 02:20
  • Didn't you read the warning message???? – IRTFM Mar 12 '19 at 02:24

1 Answers1

1

Use factor and specify levels explicitly from data

library(dplyr)

nd_data <- data %>% 
              prettyNum(big.mark = ".") %>% 
              factor(., levels = prettyNum(levels(data), big.mark = "."))

levels(data)
#[1] "(6.802,649.6]" "(649.6,1289]"  "(1289,1929]"   "(1929,2568]"   "(2568,3211]"  

levels(nd_data)
#[1] "(6.802,649.6]" " (649.6,1289]" "(1.289,1.929]" "(1.929,2.568]" "(2.568,3.211]"

data

set.seed(1234)
data <- c(rnorm(25, 2000, 500), 19, 10)
data <- data %>% cut(., breaks = 5, dig.lab = 4)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213