1

I am trying to write a generic function in R to generate this sequence: 1 4 3 6 5 8 7 10 9 12 for the first n=100 numbers.

I have tried to generate two vectors, one for odd numbers starting 1 and one for even numbers starting 4 and trying to concatenate c(x[i],y[i])use a loop to generate the sequence.

x<-seq.int(1,100,2)
y<-seq.int(4,100,2)
seqxy<-c(x,y){
for(i in 1:12){seqxy[i]<-c(x[i],y[i])
}
return(seqxy)

}

I get an error message while trying to run the loop. "Error: object 'seqxy' not found"

Jinlin Lau
  • 13
  • 2
  • You can directly do `c(rbind(x, y))` to select them alternately as showed in the link. As `x` and `y` are not of same length you might want to remove the last value from the combination. – Ronak Shah May 31 '19 at 03:30
  • 2
    @RonakShah - It's also a regular sequence - `1:100 + c(0,2)` – thelatemail May 31 '19 at 03:42
  • Even though there are nicer ways to do it, as it has been pointed out, your reasoning is not wrong. Just change `seqxy<-c(x,y){` to `seqxy <- c()` and `seqxy[i]<-c(x[i],y[i])` to `seqxy <- c(seqxy, x[i], y[i])` – bpbutti May 31 '19 at 03:45

1 Answers1

2

You can generate two vectors of length 100, and use elements from each depending on whether the current index is odd or even:

x = 1:100
y = 3:102

ifelse(seq_along(x) %% 2, x, y)

Output:

[1]   1   4   3   6   5   8   7  10   9  12  11  14 ...
Marius
  • 58,213
  • 16
  • 107
  • 105