[R] convert decimals to fractions - sorted

Muhammad Subianto msubianto at gmail.com
Tue Jul 25 19:02:17 CEST 2006


Dear all,
Based on my question a few months ago
https://stat.ethz.ch/pipermail/r-help/2006-January/086952.html
and solved with
https://stat.ethz.ch/pipermail/r-help/2006-January/086955.html
https://stat.ethz.ch/pipermail/r-help/2006-January/086956.html
and from
https://stat.ethz.ch/pipermail/r-help/2006-January/086958.html

frac.fun <- function(x, den){
    dec <- seq(0, den) / den
    nams <- paste(seq(0, den), den, sep = "/")
    sapply(x, function(y) nams[which.min(abs(y - dec))])
}
#######################
frac.fun(c(0, 1, 0.8266667, .066666, 0.2666666), 75)

Now, I have a dataset something like this:

a <-"1 0
    1 0.095238095238095
    1 0.214285714285714
   -1 0.5
    1 0.309523809523810
   -1 0.0476190476190476
    1 0.404761904761905
    1 0.119047619047619
   -1 0.214285714285714
   -1 0.309523809523810
    1 0
    1 0
    1 0.404761904761905
    1 0.095238095238095
    1 0.047619047619047
    1 0.380952380952381
    1 0.214285714285714
    1 0.523809523809524
    1 0
    1 0.095238095238095"

First, I make it as fractions and then sorted.
I have played around to make it sort, but it didn't succes.

df <- read.table(textConnection(a))
library(MASS)
as.fractions(as.numeric(df[,2]))
cbind(table(df[,2], df[,1]), summary(as.factor(df[,2])))
table(frac.fun(as.numeric(df[,2]),42), df[,1])
> table(frac.fun(as.numeric(df[,2]),42), df[,1])

        -1 1
  0/42   0 4
  13/42  1 1
  16/42  0 1
  17/42  0 2
  21/42  1 0
  22/42  0 1
  2/42   1 1
  4/42   0 3
  5/42   0 1
  9/42   1 2
>

How to make the result as sort (to increase) like this,

        -1 1
  0/42   0 4
  2/42   1 1
  4/42   0 3
  5/42   0 1
  9/42   1 2
  13/42  1 1
  16/42  0 1
  17/42  0 2
  21/42  1 0
  22/42  0 1

Thank's for any help.

Best, Muhammad Subianto



More information about the R-help mailing list