How to generate a Sequence From a Given sequence

89 views Asked by At

I am trying to generate a sequence

for Example as shown below ::

> s
[1]  1  5  7 10 

>s.Generated_Seq 
[1]  1 2 9 10 13 14 19 20 

> s
[1]  2 5 7 10 

>s.Generated_Seq 
[1]  3 4 9 10 13 14 19 20 

Note : when sequence is started from 1 its generated sequence should start from 1 only and if sequence is started from 2 or 6 or 15 or any number generated sequence should be multiple of that number.

2

There are 2 answers

0
akrun On BEST ANSWER

We can create a function that takes a vector as input argument and returns the transformed output based on the logic described

f1 <- function(vec){
  if(vec[1]==1) {  #if the first element is 1
   #append the first element with the twice multiplied other elements
      c(vec[1], 2*vec[-1]) 
   #or else just multiply the vector with the first element
  } else vec*vec[1]
 }

f1(v1)
#[1]  1 10 14 20

f1(v2)
#[1]  4 10 14 20

data

v1 <- c(1, 5, 7, 10)
v2 <- c(2, 5, 7, 10)
2
Swapnil On
v1 <- c(1, 5, 7, 10)
v2 <- c(2, 5, 7, 10)

ifelse(rep(v1[1],length(v1))==1,c(v1[1],2*v1[-1]), 2*v1)
# [1]  1 10 14 20

ifelse(rep(v2[1],length(v2))==1,c(v2[1],2*v2[-1]), 2*v2)
# [1]  4 10 14 20

The reason for doing rep(v2[1],length(v2)) instead of just doing v2[1]==1 is that ifelse returns a value with the same length as ‘test’. So we basically do the test same number of times as length of vector so that we can return the complete vector from ifelse