str_pad從stringr:
library(stringr)
pad_if = function(x, cond, n, fill = "0") str_pad(x, n*cond, pad = fill)
s = str_split_fixed(names,"(?=\\d)",2)
# [,1] [,2]
# [1,] "apple" ""
# [2,] "banana" ""
# [3,] "orange" ""
# [4,] "apple" "1"
# [5,] "apple" "2"
# [6,] "apple" "10"
# [7,] "apple" "11"
# [8,] "banana" "2"
# [9,] "banana" "12"
paste0(s[,1], pad_if(s[,2], cond = nchar(s[,2]) > 0, n = max(nchar(s[,2]))))
# [1] "apple" "banana" "orange" "apple01" "apple02" "apple10" "apple11" "banana02" "banana12"
這也延伸到案件就像去從c("a","a2","a20","a202")
到c("a","a002","a020","a202")
,該其他方法不包括。
的stringr包基於stringi,其中有在這裏使用的所有相同的功能,我猜。
的sprintf自基部,具有一個類似的方法:
pad_if2 = function(x, cond, n, fill = "0")
replace(x, cond, sprintf(paste0("%",fill,n,"d"), as.numeric(x)[cond]))
s0 = strsplit(names,"(?<=\\D)(?=\\d)|$",perl=TRUE)
s1 = sapply(s0,`[`,1)
s2 = sapply(sapply(s0,`[`,-1), paste0, "")
paste0(s1, pad_if2(s2, cond = nchar(s2) > 0, n = max(nchar(s2))))
pad_if2
具有比pad_if
少一般用途,因爲它需要x
是強制轉換到數字。這裏的每一步幾乎都比上面提到的包的相應代碼更笨拙。
'sub(「([a-z])([0-9])$」,「\\ 10 \\ 2」,names)'help you? – etienne
@etienne是的!你能否解釋替換的「\\ 10 \\ 2」結構? – ano
我加了一個解釋的答案。 – etienne