5

我们正在寻找具有以下序列的向量:

1,4,5,8,9,12,13,16,17,20,21,...

从 1 开始,然后跳过 2 个数字,然后添加 2 个数字,然后跳过 2 个数字,依此类推,不要超过 2000。我们还需要反序列2,3,6,7,10,11,...

4

6 回答 6

5

我们可以使用循环向量来过滤序列

(1:21)[c(TRUE, FALSE, FALSE, TRUE)]
 [1]  1  4  5  8  9 12 13 16 17 20 21
于 2021-10-08T19:39:19.223 回答
4

这是一种使用 rep 和 cumsum 的方法。实际上,“将 1(连续 #s)和 3(跳过两个)的交替增量相加。”

cumsum(rep(c(1,3), 500))

cumsum(rep(c(3,1), 500)) - 1
于 2021-10-08T19:34:51.563 回答
1

自己有这个——head(sort(c(seq(1, 2000, 4), seq(4, 2000, 4))), 20)

于 2021-10-08T19:33:56.510 回答
1

You may arrange the data in a matrix and extract 1st and 4th column.

val <- 1:100
sort(c(matrix(val, ncol = 4, byrow = TRUE)[, c(1, 4)]))

# [1]   1   4   5   8   9  12  13  16  17  20  21  24  25  28  29  32  33
#[18]  36  37  40  41  44  45  48  49  52  53  56  57  60  61  64  65  68
#[35]  69  72  73  76  77  80  81  84  85  88  89  92  93  96  97 100
于 2021-10-09T05:09:46.827 回答
1

我们可以尝试如下

> (v <- seq(21))[v %% 4 %in% c(0, 1)]
 [1]  1  4  5  8  9 12 13 16 17 20 21
于 2021-10-08T21:06:28.857 回答
0

一个整洁的选择。

library(purrr)
library(dplyr)

map_int(1:11, ~ case_when(. == 1 ~ as.integer(1),
                          . %% 2 == 0 ~ as.integer(.*2),
                          T ~ as.integer((.*2)-1)))

#  [1]  1  4  5  8  9 12 13 16 17 20 21
于 2021-10-08T21:05:12.710 回答