-2

I have a for loop that generate each time 2 vectors of the same length (length can vary for each iteration) such as:

>aa  
[1] 3 5  

>bb  
[1] 4 8

I want to create a sequence using each element of these vectors to obtain that:

>zz  
[1] 3 4 5 6 7 8

Is there a function in R to create that?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
fabSir
  • 39
  • 4

3 Answers3

3

We can use Mapto get the sequence of corresponding elements of 'aa' , 'bb'. The output is a list, so we unlist to get a vector.

unlist(Map(`:`, aa, bb))
#[1] 3 4 5 6 7 8

data

aa <- c(3,5)
bb <- c(4, 8)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

One can obtain a sequence by using the colon operator : that separates the beginning of a sequence from its end. We can define such sequences for each vector, aa and bb, and concatenate the results with c() into a single series of numbers.

To avoid double entries in overlapping ranges we can use the unique() function:

zz <- unique(c(aa[1]:aa[length(aa)],bb[1]:bb[length(bb)]))
#> zz
#[1] 3 4 5 6 7 8

with

aa <- c(3,5)
bb <- c(4,8)
RHertel
  • 23,412
  • 5
  • 38
  • 64
1

Depending on your desired output, here are a few more alternatives:

> do.call("seq",as.list(range(aa,bb)))
[1] 3 4 5 6 7 8

> Reduce(seq,range(aa,bb)) #all credit due to @BrodieG
[1] 3 4 5 6 7 8

> min(aa,bb):max(aa,bb)
[1] 3 4 5 6 7 8
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198