RE: [R] Rounding fractional numbers to nearest fraction

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Thu 26 May 2005 - 04:54:34 EST

> From: Ken Termiso
>
> Thx for the help...
>
> mdiv <- function(dec)
> {
> dec <- dec * 4
> dec <- round(dec, 0)
> dec <- dec / 4
> dec
> }
>
> where m is a matrix --
>
> m1 <- apply(m, 1, mdiv)

You don't need the apply():

> m <- matrix(runif(6), 2, 3)
> m

[,1] [,2] [,3]
[1,] 0.6885473 0.4598892 0.2738169
[2,] 0.2393461 0.8863284 0.7891100
> round(m * 4) / 4

[,1] [,2] [,3]
[1,] 0.75 0.5 0.25
[2,] 0.25 1.0 0.75

> ...but it looks like as.integer(x.1*4)/4 or
> (round(x.1*4,0))/4 might be
> easier...

Be careful: as.integer() trucate the fractional part (so as.integer(1.999) is 1 intead of 2), which may not be what you want.

Andy

> thx again,
> ken
>
> >From: james.holtman@convergys.com
> >Subject: Re: [R] Rounding fractional numbers to nearest fraction
> >Date: Wed, 25 May 2005 14:30:44 -0400
> >
> >
> >
> >
> >
> > > x.1
> > [1] 1.07 1.11 1.27 1.59 0.97 0.76 2.23 0.98 0.71 0.88 1.19 1.02
> > > as.integer(x.1*4)/4
> > [1] 1.00 1.00 1.25 1.50 0.75 0.75 2.00 0.75 0.50 0.75 1.00 1.00
> > >
> >
> >Jim
> >__________________________________________________________
> >James Holtman "What is the problem you are trying to solve?"
> >Executive Technical Consultant -- Convergys Labs
> >james.holtman@convergys.com
> >+1 (513) 723-2929
> >
> >
> >
> > "Ken Termiso"
> >r-help@stat.math.ethz.ch
> > om> cc:
> > Sent by: Subject:
> [R] Rounding
> >fractional numbers to nearest fraction
> > r-help-bounces@stat.m
> > ath.ethz.ch
> >
> >
> > 05/25/2005 13:27
> >
> >
> >
> >
> >
> >Hi all,
> >
> >I've got a matrix of fractional data that is all positive
> and greater than
> >zero that I would like to "loosely" classify, for lack of a
> better word. It
> >
> >looks something like this :
> >
> >1.07 1.11 1.27 1.59 0.97 0.76
> >2.23 0.98 0.71 0.88 1.19 1.02
> >
> >
> >What I'm looking for is a way to round these numbers to the
> nearest 0.25,
> >i.e. the above matrix would be transformed to :
> >
> >1.00 1.00 1.25 1.50 1.00 0.75
> >2.25 1.00 0.75 1.00 1.25 1.00
> >
> >
> >Anyone have a clever way to do this??
> >
> >Ken
> >
> >______________________________________________
> >R-help@stat.math.ethz.ch mailing list
> >https://stat.ethz.ch/mailman/listinfo/r-help
> >http://www.R-project.org/posting-guide.html
> >
> >
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help