[R] non permanent change of vector values

Duncan Murdoch murdoch at stats.uwo.ca
Wed Jun 20 12:53:42 CEST 2007


On 20/06/2007 6:46 AM, Federico Calboli wrote:
> Hi All,
> 
> I have the following problem: I have a vector
> 
> x = rep(0,15)
> x[1:2] = 1
> x
>   [1] 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
> 
> I need to be able to call that vector 'x' so that if condition 'A' is true, only 
> the first value is kept 'as is' and all the others are put to 0
> 
> if(A == T)
> 
> function(x) with x returning 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> 
> and if 'A' is false the second value is kept 'as is' and all the others are put to 0
> 
> if(A == F)
> 
> function(x) with x returning 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
> 
> BUT, and that's the rub, I need x to changed in a *non permanent* way, so that 
> at the end x is still
> 
> x
>   [1] 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
> 
> (that is because condition 'A' might be called again and could be different in 
> it's T/F state from previous calls).

Simply make a function that does what you want:

modifyx <- function(x, A) {
   if (A) x[-1] <- 0
   else x[-2] <- 0
   x
}

then call your function by passing modifyx(x, A) instead of just x.

You don't need to put A or x in the argument list of the function, but 
it probably makes sense to do so.

Duncan Murdoch



More information about the R-help mailing list