【问题标题】:Count alphabetic to numeric and numeric to alphabetic transitions计算字母到数字和数字到字母的转换
【发布时间】:2020-11-11 16:22:12
【问题描述】:

我有一些数据,现在我必须计算从字母到数字或从数字到字母的转换次数。

dd <- c(text="S4FDD-S4DF5D_S54F4SDF4","eDC54E_EG5SF3543+TDX32RF","CVB5+5VN7NLC2_3LM70LCM8","1VPLF3LPD5P6OK7POD8KP9OASD9POA0")

例如。在dd[1]:

S4FDD-S4DF5D_S54F4SDF4 == 6 (Alphabetic to number Count)
                                          & 
                       == 5 (Number to Alphabetic Count)

我尝试使用此功能,但失败了:

stri_count_boundaries(dd, type="character")

【问题讨论】:

  • 6 alpha to number count, 5 number to alpha count ...你能解释一下这到底是什么意思吗?

标签: r regex stringi


【解决方案1】:

这是使用lengths + gregexpr 的基本 R 选项:

> lengths(gregexpr("[[:alpha:]]\\d+",dd))
[1] 6 4 5 8

> lengths(gregexpr("\\d+[[:alpha:]]",dd))
[1] 5 3 4 8

【讨论】:

  • 不需要regmatcheslengths(gregexpr("[[:alpha:]]\\d", dd))lengths(gregexpr("\\d[[:alpha:]]", dd)) 已经可以了。
【解决方案2】:

如果我对您的理解正确,您想数一数您遇到字母后跟数字的次数,反之亦然。

你可以在这里使用str_count

library(stringr)
str_count(dd, '[A-Z]\\d')
#[1] 6 4 5 8

str_count(dd, '\\d[A-Z]')
#[1] 5 3 4 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多