在R

时间:2018-05-30 15:26:07

标签: r string

我在R中有一个列,每个元素都是这样的 “005443333332222222211023222101110009988877665 有没有办法从非零数字的起始位置/首次出现中找到连续零的数量?对于上述情况将是2

1 个答案:

答案 0 :(得分:3)

一种方法是使用RegEx关闭前导零,然后计算字符:

string <- "005443333332222222211023222101110009988877665"

# the regex pattern (0+) matches one or more zeros, but only if they
# are at the beginning of the string, and captures in group 1

strLength <- nchar(gsub("^(0+).*","\\1", string))


print(strLength)
[1] 2

编辑:要处理没有任何前导零的情况,你需要先检查字符串是否以零开头:

strLength <- ifelse(grepl("^0+.*", string) == TRUE,nchar(gsub("^(0+).*","\\1", string)),0)

因为如果你的字符串是“123456”,当没有前导零时,我的第一个答案将返回6。