2

Suppose I have this series of numbers in a vector:

vec <- c(1,2,3,4,5)           # just an example, numbers could be far higher

How can I programmatically divide these numbers into equally-spaced intervals ranging between 0-1, such that I get:

for

  • 1: 0
  • 2: 0, 1
  • 3: 0, 0.5, 1
  • 4: 0, 0.33, 0.66, 1
  • 5: 0, 0.25, 0.50, 0.75, 1
  • and so on.

Any idea?

Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
  • 1
    Maybe: `seq(0, 1, length.out = 5)` ? Try: `lapply(1:5, function(i) seq(0, 1, length.out = i))` – zx8754 Sep 27 '21 at 13:23
  • Are you asking "how do I find the maximum, and then divide that by the number of intervals" or are you asking "does 'r' have some functionality to do this already"? – Gem Taylor Sep 27 '21 at 13:24
  • @zx8754 Why not post this as answer so I can accept it? – Chris Ruehlemann Sep 27 '21 at 13:28
  • Pretty sure this is a duplicate, can't find the correct target... posted the answer below. – zx8754 Sep 27 '21 at 13:36
  • Google sent me to your own old question, that has a solution with length.out :) https://stackoverflow.com/q/64078958/680068 Still can't find the correct dupe, these things are hard to google. – zx8754 Sep 27 '21 at 13:44
  • Related: [Create multiple sequences with different lengths (length.out)](https://stackoverflow.com/questions/60233452/create-multiple-sequences-with-different-lengths-length-out) – Henrik Sep 28 '21 at 14:43

3 Answers3

2

We can use seq with length.out argument:

lapply(1:5, function(i) seq(0, 1, length.out =  i))
# [[1]]
# [1] 0
# 
# [[2]]
# [1] 0 1
# 
# [[3]]
# [1] 0.0 0.5 1.0
# 
# [[4]]
# [1] 0.0000000 0.3333333 0.6666667 1.0000000
# 
# [[5]]
# [1] 0.00 0.25 0.50 0.75 1.00

or mapply:

mapply(seq, from = 0, to = 1, length.out = 1:5)
zx8754
  • 52,746
  • 12
  • 114
  • 209
1

if I understand well maybe is somthing like this:

v <- 1:5
norm <- function(x){
  if(length(x)==1)0 else{
    (x-min(x))/(max(x)-min(x))
  }
  }
lapply(v, function(x)(norm(seq(1,x,length.out = x))))

output

[[1]]
[1] 0

[[2]]
[1] 0 1

[[3]]
[1] 0.0 0.5 1.0

[[4]]
[1] 0.0000000 0.3333333 0.6666667 1.0000000

[[5]]
[1] 0.00 0.25 0.50 0.75 1.00
Elia
  • 2,210
  • 1
  • 6
  • 18
1

Using map

library(purrr)
map(1:5, ~ seq(0, 1, length.out = .x))

-output

[[1]]
[1] 0

[[2]]
[1] 0 1

[[3]]
[1] 0.0 0.5 1.0

[[4]]
[1] 0.0000000 0.3333333 0.6666667 1.0000000

[[5]]
[1] 0.00 0.25 0.50 0.75 1.00
akrun
  • 874,273
  • 37
  • 540
  • 662