Fill in a sequence of letters based on a given order


Apologies for this naïve questions

I have the following vector

group_name <- c("red", "green", "blue")

Is there a way to generate a cyclic sequence of this string based on the output length ?
Using function char_seq as example

char_seq (group_name, length = 2) 
c("red", "green")

char_seq (group_name, length = 5)
c("red", "green", "blue", "red", "green")

Hi :slight_smile: Welcome to the forum. We can write a relatively simple function to achieve this. See my example below

group_name <- c("red", "green", "blue")

char_seq <- function(x,group_name) {
  #whole integer division
  i <- x %/% length(group_name)
  r <- x %% length(group_name)
  if(r > 0){t <- i + 1} else {t <- i}
  set <- rep(group_name,t)
  output <- set[1:x]

#>  [1] "red"   "green" "blue"  "red"   "green" "blue"  "red"   "green" "blue" 
#> [10] "red"   "green" "blue"  "red"   "green" "blue"

Created on 2020-11-23 by the reprex package (v0.3.0)

Thank you for the help.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.