[R] Odp: Programming: loop versus vector oriented

Petr PIKAL petr.pikal at precheza.cz
Fri Sep 17 14:04:08 CEST 2010

Hi Jan

Jan private <jrheinlaender at gmx.de> napsal dne 17.09.2010 12:43:40:

> Hello Petr,
> > but I think this is how your code really works. Did you try it?
> it does, but the R documentation says somewhere:
> "Warning: for() loops are used in R code much less often than in
> compiled languages. Code that takes a `whole object' view is likely to
> be both clearer and faster in R."

Yes and no. Try to go through R-Inferno from Patrick Burns. For loop is 
not necessarily slower if properly used.

Your problem was specified not very clearly because only in last mail you 
presented that what you have is 2 equal length vectors which shall give 
result of the same length. The problem is that (if I remember correctly as 
I do not keep original mails) you have 3 distinct computations based on 
values in vector1. So if you want some vectorised computation you has to 
use either switch or ifelse or cycle. However it is not necessary to do 
computation one by one as in your function but only 3 times based on 
threshold criteria.

I would do something like:

1.      make 3 distinct separate functions which compute relevant values 
from 2 vectors in a list
2.      split vectors according to thresholds to list see ?split
3.      make cycle in which for each part of list proper function is used 
something like }not very elegant.
for (i in 1:3) result[[1]] <-  if (i==1) fun1(mylist1[[i]], mylist2[[1]]) 
else if(i==2) fun2(mylist1[[i]], ylist2[[1]]) else fun3(mylist1[[i]], 
4.      reconstruct result in original vector 
cbind(unlist(mylist1), unlist(mylist2), unlist(result))


> So I am wondering in what way the "whole object view" could be applied
> to my function.
> Best regards,
>    Jan
> > > The function should work on the nth elements of the two input 
> > > and put the result into the nth element of the output vector. So it
> > > would work like c <- a + b, only instead of '+' there are more 
> > > calculations.

More information about the R-help mailing list