Include "." or "," from right to left of integers

Asked

Viewed 24 times

2

I have an array with the following integer values (or strings):

x <- c("1781818", "178181800", "92561781818", "1781810")

I’d like to put a semicolon to separate the last two digits, so they stay that way:

y <- c("17818.18", "1781818.00", "925617818.18", "17818.10")

I already researched the use of the function format and readr::parse_number , but I haven’t found a solution yet.

2 answers

3

The functions formatC and sprintf can be useful for this problem.

formatC(as.numeric(x)/100, digits = 2, 
        decimal.mark = ".", format = "f")
#[1] "17818.18"     "1781818.00"   "925617818.18"
#[4] "17818.10"

sprintf("%0.02f", as.numeric(x)/100)
#[1] "17818.18"     "1781818.00"   "925617818.18"
#[4] "17818.10"

2

Using the package str,

str_c(str_sub(x, start = 1, end = -3), str_sub(x, start = -2), sep = ".")

The function str_c concatenate strings, with a certain separator (I used ,).

The function str_sub extract substrings of a character, only need to specify where it starts and ends.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.