0

I want to generate unequally spaced numbers between 0 and 1 using seq() function. For example, seq(from=0, to=1, by=0.05) produce:

 [1] 0.00 0.05 0.10 0.15 0.20 0.25 0.30 0.35 0.40 0.45 0.50 0.55
[13] 0.60 0.65 0.70 0.75 0.80 0.85 0.90 0.95 1.00

which are basically equally spaced. What if one needs unequally spaced numbers? Thanks!

iGada
  • 599
  • 3
  • 9
  • 1
    Don't use seq:`sort(runif(20))`. – dcarlson Sep 04 '22 at 20:03
  • 1
    @dcarlson why not, as long as it is wrapped in `c(0, sort(runif(18) )1)`. Twenty unequally spaced numbers, starting a 0 and ending at 1. – Allan Cameron Sep 04 '22 at 20:06
  • I meant don't use the `seq()` function, instead use. . . I could have been clearer. The OP was not clear if 0 and 1 should be included as the bounds or just numbers within those bounds. – dcarlson Sep 04 '22 at 22:35

1 Answers1

2

If you want a random spacing between the numbers from 0 to 1 you could do:

c(0, sort(runif(18)), 1)
#>  [1] 0.0000000 0.1064290 0.1285520 0.3077092 0.3331251 0.3482024 0.3487170
#>  [8] 0.4284834 0.4714464 0.5641676 0.5668084 0.6001273 0.6634248 0.6831489
#> [15] 0.6946361 0.8032473 0.8326721 0.9049671 0.9173124 1.0000000

Or

x <- sort(runif(20))

(x - min(x))/diff(range(x))
#>  [1] 0.000000000 0.007808921 0.058158791 0.099387011 0.158935673 0.188611111
#>  [7] 0.244883988 0.246103767 0.321436647 0.670812054 0.691092865 0.723789885
#> [13] 0.734510004 0.750587586 0.787621952 0.853132449 0.893640287 0.904846238
#> [19] 0.911214558 1.000000000

Or, if you want a regular repeating unequal pattern:

c(0, cumsum(rep(c(0.04, 0.06), length = 20)))
#>  [1] 0.00 0.04 0.10 0.14 0.20 0.24 0.30 0.34 0.40 0.44 0.50 0.54 0.60 0.64 0.70
#> [16] 0.74 0.80 0.84 0.90 0.94 1.00

Or, if you are intent on using seq, you can raise the output to any power and get an unequally spaced sequence starting at 0 and ending in 1.

seq(0, 1, 0.05)^2
#>  [1] 0.0000 0.0025 0.0100 0.0225 0.0400 0.0625 0.0900 0.1225 0.1600 0.2025
#> [11] 0.2500 0.3025 0.3600 0.4225 0.4900 0.5625 0.6400 0.7225 0.8100 0.9025
#> [21] 1.0000
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87