[R] Create a vector from another vector

Robin Hankin r.hankin at noc.soton.ac.uk
Wed Aug 30 16:01:34 CEST 2006


Dear Harold

package "partitions" does almost this:



 > library(partitions)
 > x <- 1+restrictedparts(15,5)
 > x[,1:10]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]   16   15   14   13   12   11   10
[2,]    1    2    3    4    5    6    7
[3,]    1    1    1    1    1    1    1
[4,]    1    1    1    1    1    1    1
[5,]    1    1    1    1    1    1    1
      [,8] [,9] [,10]
[1,]    9   14    13
[2,]    8    2     3
[3,]    1    2     2
[4,]    1    1     1
[5,]    1    1     1
 >

HTH

Robin


On 30 Aug 2006, at 14:49, 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[1] is larger than x[1] even though it sums to 19.
>
> 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.
>
> Any hints would be greatly appreciated.
>
> Harold
>
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting- 
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743



More information about the R-help mailing list