1

I want to convert some fraction characters in a string to a decimal format, but keep the context of the rest of the string, so that:

enter image description here

becomes:

enter image description here

This answer is similar to what I'm looking to do, but when adjusted to my use case, it doesn't keep the remainder of the string, and seems to break down entirely when used on a data frame.

library(gsubfn)

calc <- function(s) {
  x <- c(if (length(s) == 2) 0, as.numeric(s), 0:1)
  x[1] + x[2] / x[3]
}

ff <- c('1 1/2', '2 3/4', '2/3', '11 1/4', '5/4')
sapply(strapplyc(ff, "\\d+"), calc)
#1.5000000  2.7500000  0.6666667 11.2500000  1.2500000

ef = c('1 1/2" ant', '2 3/4" apple', '2/3" berry', '11" 1/4 plum', '5/4" orange')
sapply(strapplyc(ef, "\\d+"), calc)
#1.5000000  2.7500000  0.6666667 11.2500000  1.2500000

df <- as.data.frame(ef)
sapply(strapplyc(df$ef, "\\d+"), calc)
#2 3 4 1 5
rsylatian
  • 429
  • 2
  • 14
  • 1
    Should the first one change to 1.5? – Andrew Jun 01 '19 at 15:22
  • `sapply(sub(" ", "+", ff), function(x) eval(parse(text=x)))` but this the accepted answer of [this near dupe](https://stackoverflow.com/questions/3480222/r-converting-data-from-fraction-to-decimal). – Rui Barradas Jun 01 '19 at 15:30

1 Answers1

1

An option would be gsubfn

gsubfn("(\\d+) (\\d+)", ~ as.numeric(x) + as.numeric(y), 
     gsubfn("(\\d+)/(\\d+)", ~ as.numeric(x)/as.numeric(y), ef))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks, getting a `Evaluation error: is.character(x) is not TRUE.` error when I try mutate the ef column: `df %>% mutate(ef = gsubfn(...)` – rsylatian Jun 01 '19 at 15:43
  • 1
    @rsylatian It is beause you column is `factor` `gsubfn` takes only `character` class. Use `as.character(ef)` – akrun Jun 01 '19 at 15:44