[R] Create a vector from another vector
murdoch at stats.uwo.ca
Wed Aug 30 16:11:59 CEST 2006
On 8/30/2006 9:49 AM, Doran, Harold wrote:
> Dear list
> Suppose I have the following vector:
> x <- c(3,4,2,5,6)
> Obviously, this sums to 20. Now, I want to have a second vector, call it
> x2, that sums to x where 5 <= x <= 20, but there are constraints.
> 1) The new vector must be same length as x
> 2) No element of the new vector can be 0
> 3) Element x2[i] of the new vector cannot be larger than element x[i] of
> the original vector
> 4) Ordering is not important
> The following would be an example of what I would want if the user
> wanted the vector x2 to sum to 19
> x2 <- c(2,4,2,5,6)
> Or, because ordering is not important, this is acceptable
> x2 <- c(3,3,2,5,6)
> Whereas this would not be appropriate
> x3 <- c(4, 2,2,5,6)
> Because element x3 is larger than x even though it sums to 19.
I don't think it's really clear what you mean by "ordering is not
x2 <- c(6,5,2,4,2)
be acceptable (a re-ordering of your first two examples), even though
x2 > x1?
It's also not clear what result you want in the usual case where there
are multiple possible answers. Do you want a randomly chosen one (from
what distribution?), or would any value satisfying the constraints be
okay? (The latter would be easiest: just start with x1, and decrement
entries until the desired sum is achieved. Whether a random value is
easy or not really depends on the desired distribution.) Do entries
need to be integer valued?
> Ideally, the function would take as input the original vector, x, and
> the number that the new vector would sum to. In this example, the vector
> could sum to any number 5 through 20.
> For example,
> myFun <- function(x, sumto) ... details ...
> Is there a preexisiting function that would already do this? I have
> spent too much (unsuccessful) time trying to write a function of my own
> but can't seem to get this to work properly.
I doubt it, because this doesn't look like a standard problem.
> Any hints would be greatly appreciated.
> [[alternative HTML version deleted]]
> R-help at stat.math.ethz.ch mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help