Reputation: 615
I have the following problem which is not entirely a programming problem but I would like to have a programmed solution for it. I'm using R.
Consider the following vector
v <- c(2,3,6,1)
I want it to be resized to an arbitrary size but sum(v) should stay the same. Effectively, I want to stretch the vector. For example, by factor 2:
v2 <- c(1,1,1.5,1.5,3,3,0.5,0.5)
When the new vector is a multiple of the old one, we can just divide the elements. However, it should work also for others sizes which are not multiples of the original vector's size, e.g. 150.
I guess I could use something like linear interpolation for this but I can't think of a simple solution now.
Upvotes: 2
Views: 2636
Reputation: 1726
you can use the rep function to do this
rep(v,each=2)/2
answer: [1] 1.0 1.0 1.5 1.5 3.0 3.0 0.5 0.5
Upvotes: 0
Reputation: 615
Ok, just found a solution. I'm new to R and to math ;)
v <- seq(1,10)
This resizes the vector by interpolating the values:
v2 <- approx(v, n=33)$y
Next, we normalize to keep the sum:
norm <- sum(v)/sum(v2)
v3 <- v2 * norm
In this example, v3 will be
[1] 0.3030303 0.3882576 0.4734848 0.5587121 0.6439394 0.7291667 0.8143939
[8] 0.8996212 0.9848485 1.0700758 1.1553030 1.2405303 1.3257576 1.4109848
[15] 1.4962121 1.5814394 1.6666667 1.7518939 1.8371212 1.9223485 2.0075758
[22] 2.0928030 2.1780303 2.2632576 2.3484848 2.4337121 2.5189394 2.6041667
[29] 2.6893939 2.7746212 2.8598485 2.9450758 3.0303030
Upvotes: 4