String Manipulation

Hi,
my question is (probably) very simple; i wanna add a character in a string at a certain place.
when i got the string: "3990", i wanna manipulate it, so that i got "39.90".
how would you approach this?

thx a lot =)

You should be able to do this with a Regular Expression – essentially you're doing the equivalent of a find and replace. I rounded up some RegEx in R resources below that should help you out:
https://maraaverick.rbind.io/2017/09/regex-resources/

1 Like

There are lots of possibilities, e.g.

library(stringi)
p1 <- stri_sub("3990", from = 1, to = 2)
p2 <- stri_sub("3990", from = 3, to = 4)
paste0(p1, ".", p2)

You can use that approach and write a function.

Another solution (without stringi package)

x <- "23232323532232"
whereDot <- 5
splitX <- substring(x, c(1, whereDot), c(whereDot - 1, nchar(x)))
paste0(splitX[1], ".", splitX[2])

"2323.2323532232"
1 Like

Is there any other possible results? like 39990, 399990.
I feel like you just want to maintain the the last two digits as decimal places.

thx so far!

the stringr version looks conveniant for me, but i will try out others as well.

true @EconKid thats what i was trying to maintain. and i did this with:

s <- "39990"
p1 <- stri_subi(s, from = 1, to = nchar(s)-2)
p2 <- stri_subi(s, from = nchar(s)-1, to = nchar(s))
paste0(p1, ".", p2)

Hi, @anon73295571,

If all data are integer-like in character format, I think this is another way.

> library(tidyverse)
> library(formattable)
> accounting(
+ "39990" %>% as.integer()/100
+ )
[1] 399.90