[R] Create a vector from another vector
Robin Hankin
r.hankin at noc.soton.ac.uk
Wed Aug 30 16:13:16 CEST 2006
I think I've got it now.
If I understand your question, try:
> x <- do.call("cbind",lapply(5:7,function(i){restrictedparts(i,
5,include.zero=FALSE)}))
> acceptable <- function(x){all(x<=c(3,4,5,2,6))}
> x[,apply(x,2,acceptable)]
[,1] [,2] [,3] [,4]
[1,] 1 2 3 2
[2,] 1 1 1 2
[3,] 1 1 1 1
[4,] 1 1 1 1
[5,] 1 1 1 1
>
rksh
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