-1

I have Age column in the data frame. Age is mentioned as 22,7 18,5 25,4 I need to replace , with decimal. How can I do that in R?

strsplit(as.character(age), ",")
[[1]]
[1] "22" "1" 

[[2]]
[1] "14" "7" 

[[3]]
[1] "19" "8" 

[[4]]
[1] "19" "7" 

[[5]]
[1] "22" "6" 

[[6]]
[1] "15" "7" 
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 5
    How did you read the data into R? We can set `dec` option, see https://stackoverflow.com/questions/6123378/how-to-read-in-numbers-with-a-comma-as-decimal-separator – zx8754 Jul 09 '18 at 18:43
  • Possible duplicate of [How to read in numbers with a comma as decimal separator?](https://stackoverflow.com/questions/6123378/how-to-read-in-numbers-with-a-comma-as-decimal-separator) – Esther Jul 09 '18 at 20:01

2 Answers2

3

A way to replace the comma with a period is to use scan with argument dec = ",".

scan(text = "22,7 18,5 25,4", dec = ",")
#Read 3 items
#[1] 22.7 18.5 25.4


y <- c("22,7", "18,5", "25,4")

scan(textConnection(y), dec = ",")
#Read 3 items
#[1] 22.7 18.5 25.4
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
2

We can use sub to replace , with . and convert to numeric

as.numeric(sub(",", ".", age))
#[1] 22.7 18.5 25.4

Or with chartr

as.numeric(chartr(",", ".", age))

data

age <- c("22,7", "18,5", "25,4")
akrun
  • 874,273
  • 37
  • 540
  • 662