3

I want to generate these two sequences:

A = c(0.25,0.50,0.75,1,0.25,0.50,0.75,0.25,0.50,0.25)
B = c(0.33,0.66,1,0.33,0.66,0.33)

with one function. I already have this:

X = 5
X = 4
rep(seq(1/(X-1),1,1/(X-1)), X-1)

but, I still need to remove some values, I did it like this, but that is not really the right way:

rep(seq(1/(X-1),1,1/(X-1)), X-1)[-c(8,11,12,14,15,16)]
rep(seq(1/(X-1),1,1/(X-1)), X-1)[-c(6,8,9)]

Is there a way to write this in a single function?

user20650
  • 24,654
  • 5
  • 56
  • 91

2 Answers2

3

One way to do this is by sequence(x:1)/x, with x taking the required value.

> f = function(x) sequence(x:1)/x
> f(4)
# [1] 0.25 0.50 0.75 1.00 0.25 0.50 0.75 0.25 0.50 0.25
> f(3)
# [1] 0.3333333 0.6666667 1.0000000 0.3333333 0.6666667 0.3333333

(This is assuming that sequence counts as one function i.e. and we don't include : and / etc.)

user20650
  • 24,654
  • 5
  • 56
  • 91
2

The sequence approach by @user20650 is a super elegant option already. Below is another one but not that concise

f <- function(x) unlist(sapply(x:1, seq)) / x

such that

> f(3)
[1] 0.3333333 0.6666667 1.0000000 0.3333333 0.6666667 0.3333333
> f(4)
 [1] 0.25 0.50 0.75 1.00 0.25 0.50 0.75 0.25 0.50 0.25
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • 1
    It concise enough ... in fact it is almost exactly how sequence used to be written before it was rewritten in C in v4.0 – user20650 Dec 31 '20 at 23:25