GeoCat333
GeoCat333

Reputation: 79

R - find highest number of repeated digits in a single number

Is there a function that could return the highest number of sequentially repeated digits for a given number?

Desired output is the 'Num_repeats' portion for the numbers below:

Number                     Num_repeats
18.25328700000000026193    9
18.09606604359100042883    3
17.95982782048729065186    0

Upvotes: 1

Views: 59

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102241

Another base R solution

df <- within(df,
             Num_repeats <- sapply(gsub("\\D","",Number,perl = TRUE),
                                   function(x) (u<-max(rle(utf8ToInt(x))$lengths))*(u>1)))

or a simpler one

df <- within(df,
             Num_repeats <- sapply(Number,
                                   function(x) (u<-max(rle(utf8ToInt(x))$lengths))*(u>1)))

such that

> df
                   Number Num_repeats
1 18.25328700000000026193           9
2 18.09606604359100042883           3
3 17.95982782048729065186           0

DATA

df <- structure(list(Number = c("18.25328700000000026193", "18.09606604359100042883", 
"17.95982782048729065186")), row.names = c(NA, -3L), class = "data.frame")

Upvotes: 1

akrun
akrun

Reputation: 887501

If it is a character column, we can split with strsplit and use rle to extract the length of adjacent repeated elements and use max to return the `max`` value

df1$Num_repeats <- sapply(strsplit(df1$Number, "[.]|"),
           function(x) with(rle(x), max(lengths)))
df1$Num_repeats[df1$Num_repeats==1] <- 0
df1
#                    Number Num_repeats
#1 18.25328700000000026193           9
#2 18.09606604359100042883           3 
#3 17.95982782048729065186           0

data

df1 <-  structure(list(Number = c("18.25328700000000026193", 
     "18.09606604359100042883", 
"17.95982782048729065186")), class = "data.frame", row.names = c(NA, 
-3L))

Upvotes: 1

Related Questions