[英]R - create a sequence of odd numbers followed by the sequence of even numbers on the same interval
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?是否有一个更简单的 function 内置于 R 或一些允许我只指定一个间隔(从 1 到 6;而不必指定从 1 到 5 和从 2 到 6)的包中,但是对数字进行排序所有奇数都出现在偶数之前?
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]
).在下面,您可以获得原始数据
x1
,它由均值为 8 的泊松分布中的 10 个整数组成( rpois(n = 10, lambda = 8)
),并合并奇数的子数据( x1[x1 %% 2 == 1]
)和偶数( 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])
You can use sequence
.您可以使用
sequence
。 The first argument of the function is the length of each sequence, from
is the starting point, and by
is the interval. function的第一个参数是每个序列的长度,
from
是起点, by
是区间。
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:或者,作为符合您要求的 function:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.