I would like to format number so that the every thousand should be separated with a space.
What I've tried :
library(magrittr)
addSpaceSep <- function(x) {
x %>%
as.character %>%
strsplit(split = NULL) %>%
unlist %>%
rev %>%
split(ceiling(seq_along(.) / 3)) %>%
lapply(paste, collapse = "") %>%
paste(collapse = " ") %>%
strsplit(split = NULL) %>%
unlist %>%
rev %>%
paste(collapse = "")
}
> sapply(c(1, 12, 123, 1234, 12345, 123456, 123456, 1234567), addSpaceSep)
[1] "1" "12" "123" "1 234" "12 345" "123 456" "123 456"
[8] "1 234 567"
> sapply(c(1, 10, 100, 1000, 10000, 100000, 1000000), addSpaceSep)
[1] "1" "10" "100" "1 000" "10 000" "1e +05" "1e +06"
I feel very bad to have written this makeshift function but as I haven't mastered regular expressions, it's the only way I found to do it. And of course it won't work if the number is converted in a scientific format.