简体   繁体   English

如何在R中的字符串中返回唯一的数字位数?

[英]How can I return the unique number of digits in a character string in R?

I have a vector of strings with 24 digits each. 我有一个向量,每个向量都有24位数字。 Each digit represents an hour, and if the digit is "0" then the rate from period 0 applies and if the digit is 1 then the rate from period 1 applies. 每个数字代表一个小时,如果数字为“ 0”,则应用从周期0开始的速率;如果数字为1,则应用从周期1开始的速率。

As an example consider the two strings below. 作为示例,请考虑下面的两个字符串。 I would like to return the number of periods in each string. 我想返回每个字符串中的句点数。 For example: 例如:

str1 <- "000000000000001122221100"
str2 <- "000000000000000000000000"

#str1: 3
#str2: 1

Any recommendations? 有什么建议吗? I've been thinking about how to use str_count from stringr here. 我一直在考虑如何从stringr使用str_count。 Also, I've searched other posts but most of them focus on counting letters in character strings, whereas this is a slight modification because the string contains digits and not letters. 另外,我搜索了其他帖子,但其中大多数都集中在对字符串中的字母进行计数,而这是一个略微的修改,因为字符串包含数字而不是字母。

Thanks! 谢谢!

这是一个丑陋的解决方案,但是这里

length(unique(unlist(strsplit(str1,split = ""))))

Here is another option by using charToRaw . 这是使用charToRaw另一个选项。

length(unique(charToRaw(str1)))
[1] 3
length(unique(charToRaw(str2)))
[1] 1

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

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