As an example; If I want to create a vector with 4 elements, the vector should be:
c(0.4,0.3,0.2,0.1)
The difference of the elements is constant and the sum of the elements is equal to 1. What is the most elegant way to create series (with desired length out, of course) like this ?
Thanks in advance.
CodePudding user response:
You can do:
distance <- 0.05
result <- seq(from = 0, to = 1, by = distance)
result <- result/sum(result)
result
[1] 0.000000000 0.004761905 0.009523810 0.014285714 0.019047619 0.023809524
[7] 0.028571429 0.033333333 0.038095238 0.042857143 0.047619048 0.052380952
[13] 0.057142857 0.061904762 0.066666667 0.071428571 0.076190476 0.080952381
[19] 0.085714286 0.090476190 0.095238095
sum(result)
[1] 1
Alternatively, you can define the sequence through the number of elements:
n_elements <- 20
result <- seq(from = 0, to = 1, length.out = n_elements)
result <- result/sum(result)
result
[1] 0.000000000 0.005263158 0.010526316 0.015789474 0.021052632 0.026315789
[7] 0.031578947 0.036842105 0.042105263 0.047368421 0.052631579 0.057894737
[13] 0.063157895 0.068421053 0.073684211 0.078947368 0.084210526 0.089473684
[19] 0.094736842 0.100000000
sum(result)
[1] 1
Yet another alternative to make sure we have non-zero elements:
result <- seq(from = 0, to = 1, length.out = n_elements 1)
result <- result[-1]/sum(result[-1])
result
[1] 0.004761905 0.009523810 0.014285714 0.019047619 0.023809524 0.028571429
[7] 0.033333333 0.038095238 0.042857143 0.047619048 0.052380952 0.057142857
[13] 0.061904762 0.066666667 0.071428571 0.076190476 0.080952381 0.085714286
[19] 0.090476190 0.095238095
sum(result)
[1] 1
