I would like to create a sequence starting at 2 and ending at 65, which increments first by 3, then by 1, then by 3, then by 1, and so on, giving an end result that looks like this:
sequence(2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65)
Does anyone know how to go about generating such a sequence?
Using recycling in R, first create all numbers between 3&65 and from that just selecting alternate pairs! and after that attach the 2 to it.
To select the alternate pairs , i choose the following pattern : c(FALSE,FALSE,TRUE,TRUE) such that first 2 are rejected and next 2 are accepted. For e.g. c(3,4,5,6)[c(FALSE,FALSE,TRUE,TRUE)] means that 3,4 are rejected and 5,6 are accepted
c(2,c(3:65)[c(F,F,T,T)])
[1] 2 5 6 9 10 13 14 17 18 21 22 25 26 29 30 33 34 37 38 41 42 45 46 49 50 53 54 57 58 61 62
[32] 65
Since I'm working on Rcpp, I thought shall just explore on that. Thanks for this question. Completed my first assignment in Rcpp :)
library(Rcpp)
cppFunction('NumericVector func(int start, int end){
int j = 0;
int len = ceil((end-start)/2);
if (end%2 != 0){
len+=1;
}
Rcpp::NumericVector result(len);
result[j++] = start;
int i = start;
while(j <= len){
if (j%2 == 0){
result[j++] = i+1;
i+=1;
}
else {
result[j++] = i+3;
i+=3;
}
}
return result;
}')
> func(2,65)
[1] 2 5 6 9 10 13 14 17 18 21 22 25 26 29 30 33 34 37 38 41 42 45 46 49 50 53 54 57 58 61 62 65
> func(2,20)
[1] 2 5 6 9 10 13 14 17 18
> func(1,10)
[1] 1 4 5 8
Easily generalizable
begin = 2
end = 65
d = c(3, 1)
l = length(d)
cumsum(c(begin, rep(d, len = (end-l)/l)))
[1] 2 5 6 9 10 13 14 17 18 21 22 25 26 29 30 33 34 37 38 41 42 45 46 49 50 53 54 57 58 61 62 65
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With