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

Time:12-19

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.

CodePudding user response:

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"
  • Related