Home > OS >  Add a space every three characters from the end
Add a space every three characters from the end

Time:05-17

I need to add a space between every 3rd character in the string but from the end. Also, ignore the element, which has a percentage %.

string <- c('186527500', '3875055', '23043', '10.8%', '9.8%')

And need to get the view: 186 527 500, 3 875 055, 23 043, 10.8%, 9.8%

CodePudding user response:

You could do:

ifelse(grepl('%', string), string, scales::comma(as.numeric(string), big = ' '))
#> [1] "186 527 500" "3 875 055"   "23 043"      "10.8%"       "9.8%" 

CodePudding user response:

Here is a base R solution with prettyNum. The trick is to set big.mark to one space character.
I use a variant of my answer to another post, but instead of returning an index to the numbers cannot be converted to numeric, the function below returns the index of the numbers that can. This is to avoid trying to put spaces in the % numbers.

check_num <- function(x){
  y <- suppressWarnings(as.numeric(x))
  if(anyNA(y)){
    which(!is.na(y))
  } else invisible(NULL)
}

string <- c('186527500', '3875055', '23043', '10.8%', '9.8%')

i <- check_num(string)
prettyNum(string[i], big.mark = " ", preserve.width = "none")
#> [1] "186 527 500" "3 875 055"   "23 043"

Created on 2022-05-16 by the reprex package (v2.0.1)

You can then assign the result back to the original string.

string[i] <- prettyNum(string[i], big.mark = " ", preserve.width = "none")

CodePudding user response:

Using format and ifelse:

ifelse(!grepl("\\D", string), format(as.numeric(string), big.mark = " ", trim = T), string)
#[1] "186 527 500" "3 875 055"   "23 043"      "10.8%"       "9.8%"       

CodePudding user response:

An idea is to reverse the strings, add the space and reverse back, i.e.

new_str <- string[!grepl('%', string)] 
stringi::stri_reverse(sub("\\s $", "", gsub('(.{3})', '\\1 ',stringi::stri_reverse(new_str))))
#[1] "186 527 500" "3 875 055"   "23 043"

Another way is via formatC, i.e.

sapply(new_str, function(i)formatC(as.numeric(i), big.mark = " ", big.interval = 3, format = "d", flag = "0", width = nchar(i)))

#        186527500       3875055         23043 
#    "186 527 500"   "3 875 055"      "23 043" 
  •  Tags:  
  • r
  • Related