Producing numeric sequences in R using standard patterns

时光总嘲笑我的痴心妄想 提交于 2019-12-04 03:07:46

This could be done using the cumsum (cumulative sum) function and rep:

> 31 + cumsum(rep(c(3, 2, 3), 9))
 [1]  34  36  39  42  44  47  50  52  55  58  60  63  66  68  71  74  76  79  82
[20]  84  87  90  92  95  98 100 103

To make sure sure the sequence stops at the right place:

> (31 + cumsum(rep(c(3, 2, 3), 10)))[1:28]
 [1]  34  36  39  42  44  47  50  52  55  58  60  63  66  68  71  74  76  79  82
[20]  84  87  90  92  95  98 100 103 106

Here is a custom function that should work in most cases. It uses the cumulative sum (cumsum()) of a sequence, and integer division to calculate the length of the desired sequence.

cseq <- function(from, to, by){
  times <- (to-from) %/% sum(by)
  x <- cumsum(c(from, rep(by, times+1)))
  x[x<=to]
}

Try it:

> cseq(36, 106, c(3,3,2))
 [1]  36  39  42  44  47  50  52  55  58  60  63  66  68  71  74  76  79  82  84  87  90  92  95  98
[25] 100 103 106

> cseq(36, 109, c(3,3,2))
 [1]  36  39  42  44  47  50  52  55  58  60  63  66  68  71  74  76  79  82  84  87  90  92  95  98
[25] 100 103 106 108

Here is a non-iterative solution, in case you need a specific element of the sequence

f <- function(x){
 d <- (x) %/% 3
 r <- x %% 3
 31 + d*8 + c(0,3,5)[r+1]
}

> f(1:10)
 [1] 34 36 39 42 44 47 50 52 55 58
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!