r - 我能合理拆分这些数字串吗?

标签 r regex string stringr

我有一堆这样的字符串:

x  <-  c("4/757.1%", "0/10%", "6/1060%", "0/0-%", "11/2055%")

它们是分数和以某种方式在某处混合在一起的所述分数的百分比值。所以例子中第一个数字的意思是 4 out of 7 是 57.1%。我可以轻松获得/(with, say, stringr::word(x, 1, sep = "/")) 之前的第一个数字,但第二个数字可以是一个或两个字符长所以我在想办法做这件事时遇到了麻烦。我不需要 % 值,因为一旦我得到数字就很容易重新计算。

任何人都可以看到这样做的方法吗?

最佳答案

一种看起来做你想做的丑陋的解决方案:

x  <-  c("4/757.1%", "0/10%", "6/1060%", "0/0-%", "11/2055%")

split_perc <- function(x,signif_digits=1){
  x = gsub("%","",x)
  if(grepl("-",x)) return(list(NA,NA))
  index1 = gregexpr("/",x)[[1]][1]+1
  index2 = gregexpr("\\.",x)[[1]][1]-2
  if(index2==-3){index2=nchar(x)-1}

  found=FALSE
  indices = seq(index1,index2)
  k=1
  while(!found & k<=length(indices))
  {
    str1 =substr(x,1,indices[k])
    num1=as.numeric(strsplit(str1,"/")[[1]][1])
    num2 = as.numeric(strsplit(str1,"/")[[1]][2])
    value1 = round(num1/num2*100,signif_digits)
    value2 = round(as.numeric(substr(x,indices[k]+1,nchar(x))),signif_digits)
    if(value1==value2)
    {found=TRUE}
    else
    {k=k+1}
  }
  if(found)
    return(list(num1,num2))
  else
    return(list(NA,NA))
}

do.call(rbind,lapply(x,split_perc))

输出:

     [,1] [,2]
[1,] 4    7   
[2,] 0    1   
[3,] 6    10  
[4,] NA   NA  
[5,] 11   20  

再举几个例子:

y = c("11/2055.003%","11/2055.2%","40/7057.1%")
do.call(rbind,lapply(y,split_perc))

     [,1] [,2]
[1,] 11   20   # default significant digits is 1, so match found.
[2,] NA   NA   # no match found since 55.1!=55.2
[3,] 40   70  

关于r - 我能合理拆分这些数字串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401152/

相关文章:

r - Shiny DT - 使用按钮选择选定行后的行

r - 使用 geom_sf 时如何更改图例形状?

r - 绘制 3D 平面(真实回归曲面)

带有正则表达式的 Java String strip

java - Android 中的 UTF-8 转换?

r - 晶格中具有不同 y 轴比例的多个面板的尺寸相同

java - 公司公司公司正则表达式

java - Java 中的正则表达式 : match groups until first symbol occurrence

string - F# 字符串构建

c++ - 从 C++ 中的 std::string 获取字节