I have a vector of strings with 24 digits each. 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.
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. 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
.
length(unique(charToRaw(str1)))
[1] 3
length(unique(charToRaw(str2)))
[1] 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.