gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:34:04 25 4
gpt4 key购买 nike

我有一堆这样的字符串:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com