-2

Some columns in my data frame have ',' and some have '.' as decimal separator.

DateTime             a    b    c
2000-01-01 00:30:00  3,4  6,1  9.5
2000-01-01 00:45:00  3,5  6,8  7.4

I would like to have '.' as a decimal separator throughout my data frame.

I have tried

df = gsub(',','.',df)

but it just gives me a new Value instead of a data frame. I also tried

df = lapply(df, function(x) as.character(gsub(",",".",df)))

but it just makes a list.

I have tried to set the columns as numeric (currently they're all characters due to earlier procedures), but it sets all values in a and b as NA.

Phil
  • 7,287
  • 3
  • 36
  • 66
mowxting
  • 1
  • 1
  • Does this answer your question? [In R print decimal comma instead of decimal point](https://stackoverflow.com/questions/29299404/in-r-print-decimal-comma-instead-of-decimal-point) – Nedinator Mar 20 '23 at 16:21
  • I snagged this from another answer. `options(OutDec= ".")`. Run this either in a script or console and it should print decimals with a period. – Nedinator Mar 20 '23 at 16:22
  • I tried is as `df %>% options(OutDec=".")` but it gives me the error message `Error in options(., OutDec = ".") : invalid argument`. – mowxting Mar 20 '23 at 16:54

2 Answers2

0

Probably the numbers with a comma as decimal separator are character strings. Convert them to numeric values like so:

library(readr)
parse_number("3,4", locale = locale(decimal_mark = ","))
#> [1] 3.4

Created on 2023-03-20 with reprex v2.0.2

dufei
  • 2,166
  • 1
  • 7
  • 18
0

You can replace , with . in all columns like this:

library(tidyverse)
df %>%
  mutate(across(everything(), ~str_replace(., ",", ".")))

If you have columns where , should not be replaced you can address the ones where the change should be implemented more specifically, e.g., like this:

library(tidyverse)
df %>%
  mutate(across(a:c, ~str_replace(., ",", ".")))

Data:

df <- data.frame(
  DateTime = c(2000-01-01, 2000-01-01),
  a = c("3,4","3.5"),
  b = c("6,1", "6,8"),
  c = c(9.5, 7.4))
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
  • I tried this solution, but it doesn't change anything in the data frame. All `,` and all `.` stay where they are. – mowxting Mar 20 '23 at 16:52
  • Have you tried with my data? There the solution works. Please post **your** data as a part of the question so we can help you – Chris Ruehlemann Mar 20 '23 at 16:54
  • Ah, thank you. I tried it with your data. It prints the correct data in the console, but it doesn't change the values in the data frame itself. How can I change that? – mowxting Mar 20 '23 at 17:00
  • You need to save the result in a new object; for example: `df_NEW <- df %>% mutate(across(a:c, ~str_replace(., ",", ".")))` – Chris Ruehlemann Mar 20 '23 at 17:01