rsylatian
rsylatian

Reputation: 429

R: Rounding only if there are more than two decimal places

I am looking to round a set of values to the nearest whole number, but only if the number has two or more decimal places. Otherwise, I want to keep the number unchanged.

It can be done using gsubfn, a regex and multiple type transformations, but is there a more elegant way of doing it?

library(gsubfn)

y <- c(210.61233,212.41, 213.2, 214)

y <- as.character(y)
as.numeric(gsubfn("(\\d+\\.\\d{2,})", ~ round(as.numeric(x), 0) ,  y))
#211.0 212.0 213.2 214.0

Upvotes: 0

Views: 449

Answers (2)

NelsonGon
NelsonGon

Reputation: 13309

This is arguably overly complicating but one could write up a simple function as follows:

y <- c(210.61233,212.41, 213.2, 214)


round_if<-function(my_vec,min_length){

my_pattern<-paste0("\\.(?=\\d{",min_length,",})")

to_replace<-grep(my_pattern,my_vec,perl=TRUE)

    my_vec[to_replace] <- round(Filter(function(x)grep(my_pattern,
                                   x,perl = TRUE),my_vec),0)
    my_vec

  }

Testing it on the above:

  round_if(y,2)
#[1] 211.0 212.0 213.2 214.0

Upvotes: 2

Cettt
Cettt

Reputation: 11981

One possibility is this:

y <- c(210.61233,212.41, 213.2, 214)

ifelse(y == round(y, 1), y, round(y))
[1] 211.0 212.0 213.2 214.0

First you check if a number changes if rounded to one digit. If not you keep it, otherwise you round it to the nearest whole number.

Upvotes: 4

Related Questions