How to round up a data.frame in R using the %> % dplyr operator?

Asked

Viewed 51 times

-1

I have a date.frame with many values with more than 2 houses after the comma, I would like to round to only 2 houses after the comma using preferably the operator %>%, if possible, as this operation is very common in my study and would not like to generate intermediate data frames..

Be this piece of my date.frame with the column IQA

a<-read.table(text = "Estacao2  IQA Ano Ano2    Epoca
1   58.5    2005    2005-01-01  Chuvoso
1   61.5    2005    2005-01-01  Seca
10  73.5    2005    2005-01-01  Chuvoso
10  74.577  2005    2005-01-01  Seca
11  68.577  2005    2005-01-01  Chuvoso
11  69  2005    2005-01-01  Seca
12  69.566  2005    2005-01-01  Chuvoso
14  75.25   2005    2005-01-01  Seca
15  52.33333333 2005    2005-01-01  Chuvoso
15  65  2005    2005-01-01  Seca
16  77.37577    2005    2005-01-01  Chuvoso
16  76.375  2005    2005-01-01  Seca
17  52.28571429 2005    2005-01-01  Chuvoso
17  54.22   2005    2005-01-01  Seca
", sep="", header = TRUE)

a

Update: replace the commas with dots, I hadn’t realized it before.

1 answer

2


With dplyr and stringr:

library(dplyr)
library(stringr)

a %>% 
  mutate(.data = ., across(.cols = IQA, .fns = ~ str_replace_all(string = ., pattern = ",", replacement = "."))) %>% 
  mutate(.data = ., across(.cols = IQA, .fns = ~ as.numeric(.))) %>% 
  mutate(.data = ., across(.cols = IQA, .fns = ~ round(x = ., digits = 2)))

#   Estacao2     IQA  Ano       Ano2   Epoca
#1         1   58.50 2005 2005-01-01 Chuvoso
#2         1   61.50 2005 2005-01-01    Seca
#3        10   73.50 2005 2005-01-01 Chuvoso
#4        10   74.58 2005 2005-01-01    Seca
#5        11   68.58 2005 2005-01-01 Chuvoso
#6        11   69.00 2005 2005-01-01    Seca
#7        12   69.57 2005 2005-01-01 Chuvoso
#8        14   75.25 2005 2005-01-01    Seca
#9        15   52.33 2005 2005-01-01 Chuvoso
#10       15   65.00 2005 2005-01-01    Seca
#11       16   77.38 2005 2005-01-01 Chuvoso
#12       16   76.38 2005 2005-01-01    Seca
#13       17   52.29 2005 2005-01-01 Chuvoso
#14       17 5422.00 2005 2005-01-01    Seca

Or delete the following line:

mutate(.data = ., across(.cols = IQA, .fns = ~ str_replace_all(string = ., pattern = ",", replacement = ".")))

and put dec = "," within the function read.table. Now you can do it like this:

a %>% 
  mutate(across(.cols = IQA, .fns = ~ round(x = as.numeric(.), 2)))
  • Note that the conversion of character is simpler when compared to the one made with factor. Look at this reply not to be confused when this occurs.

  • mutate(across(.cols = IQA, .fns = ~ round(x = as.numeric(.), 2))) is execlent

Browser other questions tagged

You are not signed in. Login or sign up in order to post.