regex - How to separate thousands with space -
this question has answer here:
- comma separator numbers in r? 3 answers
i format number every thousand should separated 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 bad have written makeshift function haven't mastered regular expressions, it's way found it. , of course won't work if number converted in scientific format.
this seems better fit format()
function rather bothering regular expressions. format()
function exists format numbers
format(c(1, 12, 123, 1234, 12345, 123456, 123456, 1234567), big.mark=" ", trim=true) # [1] "1" "12" "123" "1 234" "12 345" "123 456" # [7] "123 456" "1 234 567" format(c(1, 10, 100, 1000, 10000, 100000, 1000000), big.mark=" ", scientific=false, trim=true) # [1] "1" "10" "100" "1 000" "10 000" "100 000" # [7] "1 000 000"
Comments
Post a Comment