[R] rounding to whole number

(Ted Harding) Ted.Harding at wlandres.net
Thu Mar 20 21:04:56 CET 2014


On 20-Mar-2014 19:42:35 Kristi Glover wrote:
> Hi R User, 
> I was trying to convert a decimal value into integral (whole number). I used
> round function but some of the cells have the value less than 0.5 and it
> converted into 0. But I wanted these cell to have 1 instead of 0. Another
> way, I could multiply by 10. But l did not want it because it affected my
> results later.
> I was wondering about how I can convert 0.2 to 1. For example 
> data<-structure(list(site1 = structure(1:4, .Label = c("s1", "s2", 
> "s3", "s4"), class = "factor"), A = c(0, 2.3, 2.6, 1.3), B = c(0.5, 
> 0.17, 2.9, 3)), .Names = c("site1", "A", "B"), class = "data.frame",
> row.names = c(NA, 
> -4L))
> output<-structure(list(site1 = structure(1:4, .Label = c("s1", "s2", 
> "s3", "s4"), class = "factor"), A = c(0L, 3L, 3L, 2L), B = c(1L, 
> 1L, 3L, 3L)), .Names = c("site1", "A", "B"), class = "data.frame", row.names
> = c(NA, 
> -4L))
> 
> Thanks for your suggestions in advance.
> cheers,
> KG

Hi Kristi,
the function round() has peculiarites (because of the IEEE standard).
E.g.

  round(1+1/2)
  # [1] 2
  round(0+1/2)
  # [1] 0

i.e. in "equipoised" cases like these, it rounds to the nearest *even"
number; otherwise, if it is nearer to one integer value (above or below)
than to the other (below or above), then it rounds to the nearest integer
value. There are two unambiguous functions you could use for "equipoised"
cases, depending on which way you want to go:

  floor(1+1/2)
  # [1] 1
  floor(0+1/2)
  # [1] 0

  ceiling(1+1/2)
  # [1] 2
  ceiling(0+1/2)
  # [1] 1

The latter would certainly meet your request for "how I can convert
0.2 to 1", since

  ceiling(0.2)
  # [1] 1

But it will not round, say, (1+1/4) to the nearest integer.

On the other hand, if you want a function which rounds to the
nearest integer when not exactly halfway between, and rounds
either always up or always down when the fractional part is exactly 1/2,
then I think (but others will probably correct me) that you may have
to write your own -- say roundup() or rounddown():

  roundup <- function(x){
    if((x-floor(x))==1/2){
      ceiling(x)
    } else {round(x)}
  }

  rounddown <- function(x){
    if((x-floor(x))==1/2){
      floor(x)
    } else {round(x)}
  }

Also have a look at the help page

  ?round

Hoping this helps,
Ted.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 20-Mar-2014  Time: 20:04:20
This message was sent by XFMail




More information about the R-help mailing list