Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

r - Convert a character vector of mixed numbers, fractions, and integers to numeric

I'm trying to write an R function to convert fractions and mixed numbers to decimals. e.g.

mixedToFloat <- function(x){
    x <- sub(' ', '+', x, fixed=TRUE)
    return(unlist(lapply(x, function(x) eval(parse(text=x)))))
}

> mixedToFloat(c('1 1/2', '2 3/4', '2/3', '11 1/4', '1'))
[1]  1.5000000  2.7500000  0.6666667 11.2500000  1.0000000

This works for most of the cases I can think of, but feels a little bit hackish. Is there a more standard way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1) This uses strapplyc to extract the numbers and then calc puts them in standard form, converts them to numeric and performs the calculation:

library(gsubfn)

ff <- c('1 1/2', '2 3/4', '2/3', '11 1/4', '1')
calc <- function(s) {
    x <- c(if (length(s) == 2) 0, as.numeric(s), 0:1)
    x[1] + x[2] / x[3]
}
sapply(strapplyc(ff, "\d+"), calc)

2) A different approach is to convert each expression into valid R code and then parse and evaluate each.

sapply(sub(" ", "+", ff), function(x) eval(parse(text = x)))
##      1 1/2      2 3/4        2/3     11 1/4          1 
##  1.5000000  2.7500000  0.6666667 11.2500000  1.0000000 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...