Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

Divide numbers into equally-spaced intervals ranging between 0-1

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

Any idea?

Upvotes: 2

Views: 1395

Answers (3)

akrun
akrun

Reputation: 887148

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

Upvotes: 1

zx8754
zx8754

Reputation: 56169

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)

Upvotes: 2

Elia
Elia

Reputation: 2584

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

Upvotes: 1

Related Questions