[英]How to generate sequence with exclusions in R
我需要4個函數來生成一些數字(每個)
第一個函數根據除5、15、25等之外的n
奇數生成序列。
n=2
示例:1,1,3,3,7,7,9,9,11,11,13,13,13,17,17,...
第二個函數根據除10、20、30等之外的n
偶數生成序列。
n=2
示例:2,2,4,4,6,6,8,8,12,12,14,14,14,16,16,...
第三個函數從5到10的n
數字生成序列
例如n=2
:5,5,15,15,25,25,...
第四個函數從10到10的n
數字生成序列
n=2
示例:10,10,20,20,30,30,...
每個函數必須獲取矢量1: N
和n
作為輸入。
例如,
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
我對前兩個功能有一些決定,但是我不知道如何排除一些數字:
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
為什么不使用seq
和rep
?
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
產量
> [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.