Kay
Kay

Reputation: 157

In a 2 column dataframe how to format the 2nd column numbers to 2 decimals

Can someone explain how to change the 2nd column data in a data frame to 2 decimal points (as a part of data cleaning). I have tried the following code.

data <- as.matrix(read.table("Assessment2.txt")) 
data  

data <- data %>%  
mutate_if(is.numeric(), round, digits = 2) 
data

Upvotes: 0

Views: 446

Answers (4)

gravlax
gravlax

Reputation: 80

Try this to format specific columns:

    df %>%
    mutate(
      column1 = sprintf("%.2f", column1),
      column2 = sprintf("%.2f", column2)
    )

Where "%.<number_of_decimals>f" (f means float)

Upvotes: 0

dc37
dc37

Reputation: 16178

Here a quick example if you know the name of the second column and that this column is already in a numeric format:

In base R, you can go simple:

df[,2] <- round(df[,2], digits = 2)

Alternatively, you can use mutate from dplyr:

> df %>% mutate(b = round(b,digits = 2))
             a     b
1  -1.63728065  0.89
2  -0.77956851 -0.03
3  -0.64117693 -0.65
4  -0.68113139  0.65
5  -2.03328560 -0.43
6   0.50096356  1.77
7  -1.53179814 -0.02
8  -0.02499764  0.85
9   0.59298472  0.21
10 -0.19819542 -3.01

Data

df = data.frame(a = rnorm(10),
                b = rnorm(10))

> df
             a           b
1  -1.63728065  0.89200839
2  -0.77956851 -0.02571507
3  -0.64117693 -0.64766045
4  -0.68113139  0.64635942
5  -2.03328560 -0.43383274
6   0.50096356  1.77261118
7  -1.53179814 -0.01825971
8  -0.02499764  0.85281499
9   0.59298472  0.20516290
10 -0.19819542 -3.00804860

Upvotes: 0

Rui Barradas
Rui Barradas

Reputation: 76412

If it's just the second column, the following rounds it to 2 decimal digits.

Load the required package and create a data set.

library(dplyr)

set.seed(1234)
df <- data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10))

Now round the 2nd column to 2 digits.

df %>% mutate_at(2, round, digits = 2)
#            a     b          c
#1  -1.2070657 -0.48  0.1340882
#2   0.2774292 -1.00 -0.4906859
#3   1.0844412 -0.78 -0.4405479
#4  -2.3456977  0.06  0.4595894
#5   0.4291247  0.96 -0.6937202
#6   0.5060559 -0.11 -1.4482049
#7  -0.5747400 -0.51  0.5747557
#8  -0.5466319 -0.91 -1.0236557
#9  -0.5644520 -0.84 -0.0151383
#10 -0.8900378  2.42 -0.9359486

Upvotes: 0

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

Try this:

iris %>%  
  mutate_if(~is.numeric(.), ~round(., digits = 2))

Upvotes: 1

Related Questions