How to convert dot to comma for numerical columns in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

Most European countries use a comma in place of a decimal. Therefore, if we have a data set that contains dot as a decimal market and we need to use that four such European countries or if dot is recorded in place of comma then we can replace the dot with comma using format function as shown in the below examples.

Example1

 Live Demo

Consider the below data frame −

x1<−sample(c(1.1,1.25,1.57,2.1,2.4),20,replace=TRUE)
y1<−sample(c(20.24,21.27,20.4,20.5,20.37),20,replace=TRUE)
df1<−data.frame(x1,y1)
df1

Output

   x1    y1
1 2.40 20.50
2 2.40 20.50
3 1.25 20.40
4 2.40 20.50
5 2.10 20.24
6 1.57 20.37
7 2.10 20.37
8 2.10 21.27
9 1.25 20.50
10 1.10 20.40
11 1.25 20.40
12 2.40 20.50
13 2.40 21.27
14 1.10 21.27
15 2.10 20.40
16 2.40 21.27
17 2.10 20.24
18 1.10 20.40
19 2.10 20.40
20 1.10 21.27

Replacing dots with comma −

Example

format(df1,decimal.mark=",")

Output

   x1    y1
1 2,40 20,50
2 2,40 20,50
3 1,25 20,40
4 2,40 20,50
5 2,10 20,24
6 1,57 20,37
7 2,10 20,37
8 2,10 21,27
9 1,25 20,50
10 1,10 20,40
11 1,25 20,40
12 2,40 20,50
13 2,40 21,27
14 1,10 21,27
15 2,10 20,40
16 2,40 21,27
17 2,10 20,24
18 1,10 20,40
19 2,10 20,40
20 1,10 21,27

Example2

 Live Demo

x2<−sample(c(501.24,502.7,501.24,503.2),20,replace=TRUE)
y2<−sample(c(2.24,2.7,1.4,3.2),20,replace=TRUE)
df2<−data.frame(x2,y2)
df2

Output

   x2     y2
1 503.20 1.40
2 502.70 2.24
3 503.20 2.70
4 503.20 3.20
5 502.70 2.24
6 503.20 2.24
7 502.70 2.24
8 501.24 1.40
9 502.70 1.40
10 501.24 2.70
11 502.70 2.24
12 502.70 3.20
13 503.20 2.70
14 502.70 2.70
15 502.70 3.20
16 503.20 2.70
17 503.20 1.40
18 502.70 1.40
19 501.24 1.40
20 502.70 2.70

Replacing dots with comma −

Example

format(df2,decimal.mark=",")

Output

   x2     y2
1 503,20 1,40
2 502,70 2,24
3 503,20 2,70
4 503,20 3,20
5 502,70 2,24
6 503,20 2,24
7 502,70 2,24
8 501,24 1,40
9 502,70 1,40
10 501,24 2,70
11 502,70 2,24
12 502,70 3,20
13 503,20 2,70
14 502,70 2,70
15 502,70 3,20
16 503,20 2,70
17 503,20 1,40
18 502,70 1,40
19 501,24 1,40
20 502,70 2,70
raja
Published on 05-Feb-2021 08:54:05
Advertisements