[R] If...while...or what else??

David Winsemius dwinsemius at comcast.net
Tue Jan 13 20:39:34 CET 2009


On Jan 13, 2009, at 10:28 AM, Gabor Grothendieck wrote:

> If efficiency is not of concern then this is easy to understand:
>
> for(i in 1:5) for(j in 1:5) if (i < j) { ... }

or?:

 > xx <- expand.grid(i=1:5, j=1:5)

 > subset(xx, i < j)
    i j
6  1 2
11 1 3
12 2 3
16 1 4
17 2 4
18 3 4
21 1 5
22 2 5
23 3 5
24 4 5

--  
David Winsemius


>
>
>
> On Tue, Jan 13, 2009 at 8:20 AM, Niccolò Bassani
> <biostatistica at gmail.com> wrote:
>> Dear R users,I come to you with a quite silly question I think, but  
>> I hope
>> you can answer me...
>> That is, I've got some problems in using the if and while  
>> conditions in a
>> loop.
>> Substantially, I want to select rows in a dataset depending on an  
>> index
>> variable (suppose it ranges from 1 to 5), so to make a specific  
>> analysis
>> (homemade of course) on thie new dataset. Mi first tought has been  
>> to do a
>> double loop like this:
>>
>> for i in 1:5{
>> for j in (i+1):5{
>> data = dataset[(variable==i) | (variable==j),]
>> ##analysis
>> ##analysis
>> }
>> }
>>
>> This way I should select all the couples only once (gaining in  
>> efficiency I
>> hope). The fact is that this arrangement has a problem: that j ends  
>> up with
>> ranging from 2 to 6, not from to 2 to 5. So when I do a subsetting  
>> on the
>> dataset to obtain only the rows corresponding to the values of i  
>> and j I
>> want, when the loop comes to j = 6 I have an error, of course.
>> What I want to know is: how can I use the if or while condition in  
>> such a
>> loop to avoid the routine doing the computations for this case?  
>> I.e., can I
>> tell somehow R "Hey, if j=6, let it go and move on with the other
>> computations"?
>> Or maybe you can see a faster and better way of using the for  
>> conditions??
>>
>> I hope I made myself clear, if not I'll carify myself!!
>>
>> Thanks in advance
>> Niccolò
>>
>>       [[alternative HTML version deleted]]
>>
>>
>> ______________________________________________
>> R-help at r-project.org 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.
>>
>>
>
> ______________________________________________
> R-help at r-project.org 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.




More information about the R-help mailing list