[R] For each element in vector do...

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Tue Jan 17 15:49:24 CET 2006


Andrej Kastrin wrote:

> vector A: 0 1 2 3 0 4 5
> vector B: 0 2 3 4 0 5 6
> 
> What's the right way to do this. I still have some problems with for and 
> if statements...
>

  ?ifelse perhaps...

  > A
  [1] 0 1 2 3 0 4 5
  > B=ifelse(A>0,A+1,0)
  > B
  [1] 0 2 3 4 0 5 6

  does a sort of element-wise if-else thing. However it evaluates A+1 
for all elements. If you have something like:

  B = ifelse(A>0, slowFunction(A), 0)

  and not very many zeroes in A, you'll be doing a lot of slowFunction() 
work for nothing. In which case:

  B = numeric(length(A))
  B[A>0] = slowFunction(A[A>0])

  will only pass the necessary values of B to slowFunction() and put 
them into the right parts of B. B is initially all zeroes.

  It is left as an exercise to work out the better alternative to:

  ifelse(A>0, slowFunction(A), otherSlowFunction(A))

Barry




More information about the R-help mailing list