简体   繁体   English

计算r中字符串中的位数

[英]count number of digits in a string in r

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 following code: 我想计算每个单元格中的位数:我使用了以下代码:

str_count(data$name, '\\d+')

But I have getting the output as: 但我得到的输出为:

Name                    output_I_get
aldrinas63_rios200_2001  3
sa_c.fr.1234             1

But my desired output is as follows: 但我想要的输出如下:

name                     output
aldrinas63_rios200_2001   9
sa_c.fr.1234              4

Any help in this regard will be highly appreciated! 在这方面的任何帮助将受到高度赞赏!

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') 或者如果我们使用str_count ,删除+ as +检查一个或多个数字的模式,并将63计为第一个实例,将200为第二个,将2001为第三个(对于'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))

Try this: 试试这个:

nchar(gsub("\\D", "", data$name))

Example

s <- c("aldrinas63_rios200_2001","sa_c.fr.1234")

nchar(gsub("\\D", "", s))
#[1] 9 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM