rsylatian
rsylatian

Reputation: 429

R: Convert Fraction to Decimal within a String

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

Upvotes: 1

Views: 577

Answers (1)

akrun
akrun

Reputation: 887173

An option would be gsubfn

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

Upvotes: 1

Related Questions