user2021713
user2021713

Reputation: 49

Repeating patterns in a vector in R

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.

Upvotes: 1

Views: 85

Answers (3)

jkatam
jkatam

Reputation: 3447

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

Upvotes: 0

akrun
akrun

Reputation: 886998

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

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269481

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

Upvotes: 2

Related Questions