count number of digits in a string in r

后端 未结 2 1769
温柔的废话
温柔的废话 2020-12-20 15:56

I have a column with strings:

name
aldrinas63_rios200_2001
sa_c.fr.1234

I want to count the number of digits in each cell: I have used the

2条回答
  •  借酒劲吻你
    2020-12-20 17:03

    We can remove the elements that are not digits and count

    nchar(gsub("[^0-9]+", "", data$name))
    #[1] 9 4
    

    or if we are using str_count, remove the + as + checks for patterns of one or more digits and count 63 as first instance, 200 as second, and 2001 as third (for the first element of 'name')

    library(stringr)
    str_count(data$name, "[0-9]")
    #[1] 9 4
    

    data

    data <- structure(list(name = c("aldrinas63_rios200_2001", "sa_c.fr.1234"
     )), class = "data.frame", row.names = c(NA, -2L))
    

提交回复
热议问题