Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing dots with commas when both are used in the same column in R

I have a dataframe that looks like this:

Col1
4000
2.333.422
1,000,000
0.1

As you can see, I have some numbers that use dots as thousand separators and some that use commas. I want to replace the dots with commas, but only if a value has more than one dot in it, so that the last value that uses a dot as a decimal separator, does not get lost.
Any idea how to do this? Much appreciate any help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use a combination of grepl and gsub for a base R option:

x <- c("4000", "2.333.422", "1,000,000", "0.1")
output <- ifelse(grepl("\\..*\\.", x), gsub("\\.", ",", x), x)
output

[1] "4000"      "2,333,422" "1,000,000" "0.1"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading