0

I want to know how many digits do I have in a text variable. For example, a function that in the text "ABC234" the answer would be 3.

I tried with this:

aa=gregexpr("[[:digit:]]+\\.*[[:digit:]]*","ABC234")

I almost have it, but honestly I still dont understand the lists, so I have no idea how to get it.

Any function? Or how to manage it with my almost-option?

Thanks

GonzaloReig
  • 77
  • 1
  • 6

3 Answers3

1

Match each digit and then take the length of the returned value:

lengths(gregexpr("\\d", "ABC234"))
## [1] 3

or replace each non-digit with a zero length string and take the length of what remains:

nchar(gsub("\\D", "", "ABC234"))
## [1] 3
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

As an option you can use stringi or stringr libraries as well:

stringi::stri_count('ABC234', regex = '\\d')
# [1] 3
stringr::str_count('ABC234', '\\d')
# [1] 3
utubun
  • 4,400
  • 1
  • 14
  • 17
0

You can use the dpylr and readr package as follows:

library(readr)
library(dplyr)

string = "ABC234"
parse_number(string) %>% 
  nchar()

[1] 3
Cettt
  • 11,460
  • 7
  • 35
  • 58
MrNetherlands
  • 920
  • 7
  • 14