So I am basically looking for a more efficient way to do this:
c(seq(1, 5, 2), seq(2, 6, 2))
Is there a simpler function built in R or some of the packages that would allow me to specify just one interval (from 1 to 6; instead of having to specify from 1 to 5 and from 2 to 6), but to sort the numbers so that all the odd numbers appear before the even ones?
CodePudding user response:
Just concatenate the sub-data that contains only odd numbers of the original data and the other sub-data that contains the remaining even numbers.
In the following, you can have the original data x1
, which consists of 10 integers from a poisson distribution of mean 8 (rpois(n = 10, lambda = 8)
), and merge the sub-data of odd numbers (x1[x1 %% 2 == 1]
) and that of even numbers (x1[x1 %% 2 == 0]
).
## To prepare data
x1 <- rpois(n = 10, lambda = 8)
x1
## To sort the data so that odd numbers come earlier
c(x1[x1 %% 2 == 1], x1[x1 %% 2 == 0])
CodePudding user response:
You can use sequence
. The first argument of the function is the length of each sequence, from
is the starting point, and by
is the interval.
sequence(c(3, 3), from = c(1, 2), by = 2)
#[1] 1 3 5 2 4 6
Or, as a function that fits your request:
seqOrdered <- function(from = 1, to){
n = ceiling((to - from) / 2)
sequence(c(n, n), from = c(from, from 1), by = 2)
}
seqOrdered(1, 6)
#[1] 1 3 5 2 4 6