R- Converting Data from Fraction to Decimal

R- converting data from fraction to decimal

Here's a way I've done that in the past.

> frac <- c("1/2","1/3","1/4","1/5","1/8","2/3")
> sapply(frac, function(x) eval(parse(text=x)))
1/2 1/3 1/4 1/5 1/8 2/3
0.5000000 0.3333333 0.2500000 0.2000000 0.1250000 0.6666667

R: converting fractions into decimals in a data frame

You are probably looking for:

df[] <- apply(df, c(1, 2), function(x) eval(parse(text = x)))
df
a b c
1 1.0 2.5 4.0
2 0.5 3.0 4.5
3 2.0 3.5 5.0

eval(parse(text = x))

evaluates one expression at a time so, you need to run cell by cell.

EDIT: if some data frame elements can not be evaluated you can account for that by adding an ifelse statement inside the function:

df[] <- apply(df, c(1, 2), function(x) if(x %in% skip){NA} else {eval(parse(text = x))}) 

Where skip is a vector of element that should not be evaluated.

Converting fractions to decimals in an R vector

Finally found that solution:

x = c(1/2,5/2,7/2)
frac <- factor(x)
as.numeric(levels(frac))[frac]

Works with x = c("1/2","5/2","7/2") too

The other problem is that you have labels that differ from values
You want to convert labels to decimal values. Then use

frac <- structure(c(14L, 13L, 4L, 5L, 8L, 7L, 3L, 8L, 11L, 1L), .Label = c("10/1", "12/1", "15/1", "2/1", "3/1", "4/1", "5/1", "5/2", "6/1", "7/1", "7/2", "8/1", "8/5", "9/2"), class = "factor")
labl =attributes(frac)[1]
sapply(as.character(unlist(labl)), function(x) eval(parse(text=x)))

R: Convert Fraction to Decimal within a String

An option would be gsubfn

gsubfn("(\\d+) (\\d+)", ~ as.numeric(x) + as.numeric(y), 
gsubfn("(\\d+)/(\\d+)", ~ as.numeric(x)/as.numeric(y), ef))

R: fraction of class character to decimal - other approachs don't work

Your function works but you are not changing x in the function and returning an unchanged x.

So either return output of eval + parse directly

FractionToDecimal <- function(x) eval(parse(text=x))
sapply(dt$V2, FractionToDecimal, USE.NAMES = FALSE)
#[1] 0.00 0.00 0.50 0.75

Or store the result in x and return the changed x.

FractionToDecimal <- function(x) {
x <- eval(parse(text=x))
x
}

sapply(dt$V2, FractionToDecimal, USE.NAMES = FALSE)
#[1] 0.00 0.00 0.50 0.75

R - Converting Fractions in Text to Numeric

You can try to transform the unicode encoding to ASCII directly when reading the XML using a special return function:

library(stringi)
readHTMLTable(url,which=1, header=FALSE, stringsAsFactors=F,elFun=function(node) {
val = xmlValue(node); stri_trans_general(val,"latin-ascii")})

You can then use @Metrics' suggestion to convert it to numbers.

You could do for example, using @G. Grothendieck's function from this post clean up the Arms data:

library(XML)
library(stringi)
library(gsubfn)
#the calc function is by @G. Grothendieck
calc <- function(s) {
x <- c(if (length(s) == 2) 0, as.numeric(s), 0:1)
x[1] + x[2] / x[3]
}

url <- paste("http://mockdraftable.com/players/2014/", sep = "")

combine<-readHTMLTable(url,which=1, header=FALSE, stringsAsFactors=F,elFun=function(node) {
val = xmlValue(node); stri_trans_general(val,"latin-ascii")})

names(combine) <- c("Name", "Pos", "Hght", "Wght", "Arms", "Hands",
"Dash40yd", "Dash20yd", "Dash10yd", "Bench", "Vert", "Broad",
"Cone3", "ShortShuttle20")

sapply(strapplyc(gsub('\"',"",combine$Arms), "\\d+"), calc)

#[1] 30.000 31.500 30.000 31.750 31.875 29.875 31.000 31.000 30.250 33.000 32.500 31.625 32.875

There might be some encoding issues depending on your machine (see the comments)

How to convert all percentage data in R to decimal?

If your data is a dataframe, you can not use the sub function.
sub is for vectors.

Try using the same function but column by column
e.g.

column1 <- as.numeric(sub("%", "",data$column1,fixed=TRUE))/100

Convert all % with decimal in R

Write an auxiliary function and mutate_if based on its value.

is.percentage <- function(x) any(grepl("%$", x))

df1 %>%
mutate_if(is.percentage, ~as.numeric(sub("%", "", .))/100)
## A tibble: 3 x 4
# cola colb colc cold
# <chr> <dbl> <dbl> <dbl>
#1 hello 0.1 53 0.1
#2 good bye 0.2 67 2
#3 hi there 1 89 0.5

Convert decimals to number and fraction

This function does the basic calculation you need:

nicefrac <- function(x) {
f <- attr(MASS::fractions(x), "fracs") ## extract string representation
s <- as.numeric(strsplit(f, "/")[[1]])
res <- c(whole = s[1] %/% s[2], num = s[1] %% s[2], denom = s[2])
res
}
x <- 3353/6
nicefrac(x)
## whole num denom
## 558 5 6

Depending on how you want to print/represent this, you could (1) leave it as-is; (2) use sprintf("%d %d/%d", nicefrac[1], nicefrac[2], nicefrac[3]) to convert to a string representation; (3) write a little S3 class with a print method that does what you want (modifying MASS:::print.fractions).

r convert decimals to pretty fractions

@camille, thanks for referring to the fractional package

Below is a function that I modified to work for this problem

library(tidyverse)

decmls <- c(0.155351347,0.04003669,0.005442423,0.000727562,3.37797e-05)

prettyFractions <- function(x = NULL, smbl ="", signif = 3){
humanity <- function(y){
# y <- t$estPcnt
if (!is.na(y)){
d <- signif(y, digits = 3) %/% 1e-1

c <- signif(y, digits = 3) %/% 1e-2
m <- signif(y, digits = 3) %/% 1e-3
m1 <- signif(y, digits = 3) %/% 1e-4
m2 <- signif(y, digits = 3) %/% 1e-5

if ( y >= 0 ){
y_is_positive <- ""
} else {
y_is_positive <- "-"
}

if ( between(d, 1, 10) ) {
paste0( y_is_positive, smbl
,fractional::fractional(y, eps = 1e-02, maxConv = 20, sync = TRUE))
} else if ( between(c, 1, 10)){
paste0( y_is_positive, smbl
,fractional::fractional(y, eps = 1e-03, maxConv = 20, sync = TRUE))
} else if ( between(m, 1, 10)){
paste0( y_is_positive, smbl
,fractional::fractional(y, eps = 1e-04, maxConv = 20, sync = TRUE))
}else if( between(m1, 1, 10)){
paste0( y_is_positive, smbl
,fractional::fractional(y, eps = 1e-06, maxConv = 20, sync = TRUE))
} else {
paste0( y_is_positive, smbl
,fractional::fractional(y, eps = 1e-09, maxConv = 20, sync = TRUE))
}
} else if (is.na(y) | is.null(y)){
"-"
}
}

sapply(x, humanity)
}

options("scipen"=100, "digits"=4)

cbind(decmls
, Excel_Fractions
, prettyFracs = prettyFractions(decmls)
, diff = sapply(Excel_Fractions, function(x) eval(parse(text=x)))
- sapply(prettyFractions(decmls), function(x) eval(parse(text=x))))

decmls Excel_Fractions prettyFracs diff
1/6 "0.155351347" "1/6" "2/13" "0.0128205128205128"
1/25 "0.04003669" "1/25" "1/25" "0"
4/735 "0.005442423" "4/735" "1/183" "-0.0000223040035686409"
2/2749 "0.000727562" "2/2749" "1/1374" "-0.000000264751559783845"
3/88811 "0.0000337797" "3/88811" "1/29603" "-0.000000000760724687222706"


Related Topics



Leave a reply



Submit