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?
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
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