Home > database >  Repeating patterns in a vector in R
Repeating patterns in a vector in R

Time:02-05

If a vector is produced from a vector of unknown length with unique elements by repeating it unknown times

small_v <- c("as","d2","GI","Worm")

big_v <- rep(small_v, 3)

then how to determine how long that vector was and how many times it was repeated?

So in this example the original length was 4 and it repeats 3 times.

Realistically in my case the vectors will be fairly small and will be repeated only a few times.

CodePudding user response:

1) Assuming that there is at least one unique element in small_v (which is the case in the question since it assumes all elements in small_v are unique):

min(table(big_v))
## [1] 3

or using pipes

big_v |> table() |> min()
## [1] 3

Here is a more difficult test but it still works because small_v2[2] is unique in small_v2 even though the other elements of small_v2 are not unique.

# test data
small_v2 <- c(small_v, small_v[-2])
big_v2 <- rep(small_v2, 3)

min(table(big_v2))
## [1] 3

2) If we knew that the first element of small_v were unique (which is the case in the question since it assumes all elements in small_v are unique) then this would work:

sum(big_v[1] == big_v)
## [1] 3

CodePudding user response:

1) If the elements are all repeating and no other values are there, then use

length(big_v)/length(unique(big_v))
[1] 3

2) Or use

library(data.table)
max(rowid(big_v))
[1] 3

CodePudding user response:

small_v has length 4 ?!

Therefore I think we could do:

length(big_v)/3

output:

4

CodePudding user response:

Alternatively we could use rle with with to count the repeats

with(rle(sort(big_v)), max(lengths))

Created on 2023-02-04 with reprex v2.0.2

[1] 3
  • Related