# Change the decimal point of every value in an R data frame column.

R ProgrammingServer Side ProgrammingProgramming

To change the decimal point of every value in an R data frame column, we can use round function.

For Example, if we have a data frame called df that contains a column say X and we want to have each value with 3 decimal places then we can use the below command −

df$X<-round(df$X,3)

## Example 1

Following snippet creates a sample data frame −

x<-rnorm(20)
df1<-data.frame(x)
df1

The following dataframe is created

           x
1  -0.91562005
2  -0.71486966
3  -1.35440791
4  -0.86207755
5  -0.48550958
6   0.43145743
7   0.20498938
8  -1.06666846
9   0.42006706
10 -1.58312323
11 -3.17485910
12  0.86979277
13  0.51422397
14  0.10609016
15  1.76677390
16  0.37099348
17 -0.09970752
18 -0.44883679
19 -0.78389296
20 -0.60084347

To change the decimal point of every value in column x of df1 on the above created data frame, add the following code to the above snippet −

x<-rnorm(20)
df1<-data.frame(x)
df1$x<-round(df1$x,2)
df1

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

      x
1  -0.92
2  -0.71
3  -1.35
4  -0.86
5  -0.49
6   0.43
7   0.20
8  -1.07
9   0.42
10 -1.58
11 -3.17
12  0.87
13  0.51
14  0.11
15  1.77
16  0.37
17 -0.10
18 -0.45
19 -0.78
20 -0.60

## Example 2

Following snippet creates a sample data frame −

y<-rexp(20,3.25)
df2<-data.frame(y)
df2

The following dataframe is created

           y
1  0.12846498
2  0.45411494
3  0.07496508
4  0.32808533
5  0.11909036
6  0.29416546
7  0.12022920
8  0.21379528
9  0.10379913
10 0.32190311
11 0.52390563
12 0.20316711
13 0.03514671
14 0.11567971
15 0.44197119
16 0.17787958
17 0.03580091
18 0.25273254
19 0.09771133
20 0.04789005

To change the decimal point of every value in column y of df2 on the above created data frame, add the following code to the above snippet −

y<-rexp(20,3.25)
df2<-data.frame(y)
df2$y<-round(df2$y,4)
df2

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

        y
1  0.1285
2  0.4541
3  0.0750
4  0.3281
5  0.1191
6  0.2942
7  0.1202
8  0.2138
9  0.1038
10 0.3219
11 0.5239
12 0.2032
13 0.0351
14 0.1157
15 0.4420
16 0.1779
17 0.0358
18 0.2527
19 0.0977
20 0.0479
Published on 05-Nov-2021 05:54:26