Gau*_*hal 2 regex string r stringr
如何计算字符串向量中的尾随零.例如,如果我的字符串向量是:
x = c('0000','1200','1301','X230','9900')
Run Code Online (Sandbox Code Playgroud)
答案应该是
> numZeros
[1] 4 2 0 1 2
Run Code Online (Sandbox Code Playgroud)
我不想使用多个,ifelse
因为我认为应该存在更优雅和更快的解决方案.我尝试使用模数,就像这样
y = as.integer(x)
numZeros = (!(y%%10000))+(!(y%%1000))+(!(y%%100))+(!(y%%10))
Run Code Online (Sandbox Code Playgroud)
但这需要两个条件才能成真.
然后使用stringr
包并创建了一个解决方案,但它非常冗长.
library(stringr)
numZeros =
4*str_detect(x,"0000") +
3*str_detect(x,"[1-9 A-Z]000") +
2*str_detect(x,"[1-9 A-Z]{2}00") +
str_detect(x,"[1-9 A-Z]{3}0")
Run Code Online (Sandbox Code Playgroud)
另外,我无法通过查看定义来弄清楚是否str_detect
使用.ifelse
str_detect
我找到了一个简单的基础解决方案R
:
x <- c('0000','1200','1301','X230','9900')
nchar(x) - nchar(sub("0*$", "", x))
# > nchar(x) - nchar(sub("0*$", "", x))
# [1] 4 2 0 1 2
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
339 次 |
最近记录: |