【发布时间】:2018-05-30 15:26:07
【问题描述】:
我在 R 中有一个列,每个元素都像这样 '005443333332222222211023222101110009988877665 有没有办法从起始位置/非零数字的第一次出现找到连续零的数量?对于上述情况将是 2
【问题讨论】:
-
是字符串还是数字?如果是字符串可能是
as.vector(regexpr('[1-9]', str1)-1)
我在 R 中有一个列,每个元素都像这样 '005443333332222222211023222101110009988877665 有没有办法从起始位置/非零数字的第一次出现找到连续零的数量?对于上述情况将是 2
【问题讨论】:
as.vector(regexpr('[1-9]', str1)-1)
一种方法是使用 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。
【讨论】:
gsub 函数的输出长度,这只是前导零。