那種難看的-A解決方案,似乎做你想要什麼:
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
非常感謝! – Mart
奇怪的是,我只是在一個月後發現了一個bug - 「11/11100%」似乎有問題,應該是11和11,但是這個函數返回11和1.我不好,因爲沒有給出100個例子%在開始。但是目前爲止,所有其他案例都完美無缺--10,10,10,11,11,12,12和12。 – Mart