简体   繁体   English

如何在R中生成带有排除项的序列

[英]How to generate sequence with exclusions in R

I need 4 functions that generate some numbers (each) 我需要4个函数来生成一些数字(每个)

  1. First function generates sequence from n odd numbers except 5, 15, 25, etc... 第一个函数根据除5、15、25等之外的n奇数生成序列。

    example with n=2 : 1, 1, 3, 3, 7, 7, 9, 9, 11, 11, 13, 13, 17, 17,... n=2示例:1,1,3,3,7,7,9,9,11,11,13,13,13,17,17,...

  2. Second function generates sequence from n even numbers except 10, 20, 30, etc... 第二个函数根据除10、20、30等之外的n偶数生成序列。

    example witn n=2 : 2, 2, 4, 4, 6, 6, 8, 8, 12, 12, 14, 14, 16, 16,... n=2示例:2,2,4,4,6,6,8,8,12,12,14,14,14,16,16,...

  3. Third function generates sequence from n numbers from 5 by 10 第三个函数从5到10的n数字生成序列

    example witn n=2 : 5, 5, 15, 15, 25, 25,... 例如n=2 :5,5,15,15,25,25,...

  4. Fourth function generates sequence from n numbers from 10 by 10 第四个函数从10到10的n数字生成序列

    example witn n=2 : 10, 10, 20, 20, 30, 30,... n=2示例:10,10,20,20,30,30,...

Each function has to get vector 1: N and n as inputs. 每个函数必须获取矢量1: Nn作为输入。

For example, 例如,

f1(1:10, 3)
> 1, 1, 1, 3, 3, 3, 7, 7, 7, 9

f2(1:5, 10)
> 2, 2, 2, 2, 2

f3(1:15, 5)
> 5, 5, 5, 5, 5, 15, 15, 15, 15, 15, 25, 25, 25, 25, 25

f4(1:2, 1)
> 10, 20

I have some decision for first two functions but I don`t know how to exclude some numbers: 我对前两个功能有一些决定,但是我不知道如何排除一些数字:

f1 <- function(x) 2*((x-1) %/% 10) + 1 # goes 1, 3, 5, etc for n = 10
f2 <- function(x) 2*((x-1) %/% 10 + 1) # goes 2, 4, 6, etc for n = 10

why not use seq and rep ? 为什么不使用seqrep

n = 25
nrep = 2 # number of repetitions

by5 <- sort(rep(seq(5, n, by = 10), nrep )) # numbers from 5 by 10
by5 

by10 <- sort(rep(seq(10, n, by = 10), nrep )) # numbers from 10 by 10 
by10

odd <- sort(rep(seq(1, n, by = 2), nrep )) # odd number
odd[!odd %in% by5] # remove all the by5 values

even <- sort(rep(seq(2, n, by = 2), nrep )) # Even numbers
even[!even %in% by10] # remove all the by 10 values

output 产量


> [1]  5  5 15 15 25 25
> [1] 10 10 20 20
> [1]  1  1  3  3  7  7  9  9 11 11 13 13 17 17 19 19 21 21 23 23
> [1]  2  2  4  4  6  6  8  8 12 12 14 14 16 16 18 18 22 22 24 24.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM