带库的 R 分数(质量)

R fractions with library(MASS)

我有一长串字符格式的数字(大约 50000 个术语),可以使用 "as.numeric" 非常快速地转换为数字:

y = c("-1", "1", "1", ...)

问题是我扩展了功能以包含分数并调用

    y = c("-1/2", "1", "1", ...)
    y = as.numeric(y);

产生一条 "NAs introduced by coercion" 警告消息,同时调用

 sapply(y , function(x) {

     eval(parse(text=x));
  });

问题已解决,但执行时间更长。有更好的方法吗?

eval(parse(text)) 非常慢 - 因为您知道自己将要做什么,所以您可以编写一个更快的函数:

y = c("-1/2", "1", "1", "1/2")
fixnums <- function(x){
  temp <- as.numeric(x)
  temp[is.na(temp)] <- lapply(strsplit(x[is.na(temp)], "/"), function(x) as.numeric(x[1])/as.numeric(x[2]))
  unlist(temp)
}
fixnums(y)

更快的版本,避免了 lapply,@DavidArenburg 在下面的评论中建议:

davidfixnums <- function(x){
  temp <- as.numeric(x)
  temp2 <- as.numeric(unlist(strsplit(y[is.na(temp)], "/", fixed = TRUE)))
  temp[is.na(temp)] <- temp2[c(T, F)]/temp2[c(F, T)]
  temp
}

一些基准测试,使用@akrun 和@DavidArenburgs 建议:

library(microbenchmark)
set.seed(1234)
y <- sample(c("-1/2", "1", "1", "1/2"), 10000, replace = TRUE)

akrunfixnums <- function(y){
  x1 <- as.numeric(y)
  x1[is.na(x1)] <- vapply(y[is.na(x1)], function(x) 
    eval(parse(text=x)), numeric(1))
  x1
}

microbenchmark(fixnums(y), davidfixnums(y), akrunfixnums(y))

Unit: milliseconds
            expr        min         lq       mean     median        uq       max neval cld
      fixnums(y)  22.643745  23.157345  25.326465  23.435554  23.98544 154.16316   100  b 
 davidfixnums(y)   6.676234   6.778378   6.957626   6.824459   6.93025  10.12763   100 a  
 akrunfixnums(y) 845.404840 858.031737 869.886625 865.255363 875.54351 960.86497   100   c