How to display numbers with decimal in R data frame column?

R ProgrammingServer Side ProgrammingProgramming

To display numbers with decimal in R data frame column, we can use format function with round function and nsmall argument.

For Example, if we have a data frame called df that contains an integer column say X then we can display numbers in X with 2 decimal places by using the below command −

df$X<-format(round(df$X,2),nsmall=2)

Example 1

Following snippet creates a sample data frame −

x<-rpois(20,5)
df1<-data.frame(x)
df1

The following dataframe is created

   x
1  6
2  1
3  6
4  5
5  3
6  5
7  7
8  2
9  5
10 1
11 5
12 3
13 3
14 8
15 6
16 8
17 4
18 3
19 5
20 5

To convert column x values to two decimal places values on the above created data frame, add the following code to the above snippet −

x<-rpois(20,5)
df1<-data.frame(x)
df1$x<-format(round(df1$x,2),nsmall=2)
df1

Output

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

     x
1  6.00
2  1.00
3  6.00
4  5.00
5  3.00
6  5.00
7  7.00
8  2.00
9  5.00
10 1.00
11 5.00
12 3.00
13 3.00
14 8.00
15 6.00
16 8.00
17 4.00
18 3.00
19 5.00
20 5.00

Example 2

Following snippet creates a sample data frame −

y<-rpois(20,10)
df2<-data.frame(y)
df2

The following dataframe is created

    y
1  22
2   8
3   9
4  12
5  10
6  16
7  10
8  13
9  11
10  8
11  9
12 10
13 10
14  7
15  9
16  9
17 15
18 14
19 10
20 11

To convert column y values to three decimal places values on the above created data frame, add the following code to the above snippet −

y<-rpois(20,10)
df2<-data.frame(y)
df2$y<-format(round(df2$y,3),nsmall=3)
df2

Output

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

      y
1  22.000
2  8.000
3  9.000
4  12.000
5  10.000
6  16.000
7  10.000
8  13.000
9  11.000
10 8.000
11 9.000
12 10.000
13 10.000
14 7.000
15 9.000
16 9.000
17 15.000
18 14.000
19 10.000
20 11.000
raja
Published on 05-Nov-2021 05:59:31
Advertisements