[R] How to make a code last until a condition is completed ?

Boris Steipe boris.steipe at utoronto.ca
Thu Mar 20 19:56:54 CET 2014


This is really a question of programming logic - not of R per se.

If I understand your problem correctly, the preferred approach is not to create your paths all at once, but individually, and check that they fulfil your requirements as you generate them. Keep on doing this until you have enough valid paths.

(Below: "teaching code" for illustration...)

set.seed(112358)
#####
acceptedPaths <- 0
nRequired <- 100
paths_x <- rep(0.0, nRequired)
paths_y <- rep(0.0, nRequired)

while (acceptedPaths < nRequired) {
	
	x <- rnorm(1) * 100 
	y <- rnorm(1) * 100 
	
	if (x > -100 && x < 100 && y > -100 && y < 100 ) {
		# this pair is good ...
          acceptedPaths <- acceptedPaths + 1
		paths_x[acceptedPaths] <- x
		paths_y[acceptedPaths] <- y
	}
}
######
plot(paths_x, paths_y)

Note: as you are developing your "real" function, keep a counter that aborts the loop in case a maximum number of trials is exceeded - just in case there is a bug and your >>while<< condition is never met.
 
Also: always use set.seed() when working with randomness, otherwise your code may be impossible to debug.

To answer your original question about how to manage such a test in principle, you would never ever copy/paste code to do the same thing several times and cross your fingers and hope it was often enough :-)
Rather consider this:

aPathHadToBeReplaced <- TRUE
while ( aPathHadToBeReplaced ) {
   aPathHadToBeReplaced <- FALSE 
   # check more paths
   if ( needsReplacing ) {
      # replace it, and ...
      aPathHadToBeReplaced <- TRUE  
   }
}


I hope this solves your problem.
B.






On 2014-03-20, at 9:46 AM, Gwennaël Bataille wrote:

> Dear Petr,
> Thank you for your answer. This will probably save me three lines of script, which is appreciable.
> 
> Unfortunately, this does not solve my main issue, that is:
> If my condition is not fulfilled (some points are outside the landscape), I have to go back in the script to the first step, again and again until the condition "none individual is outside the landscape" is fulfilled.
> 
> Is it a trick in R that makes that possible ? Or am I obliged to copy-paste : step 1 - step 2 - step 1 -  step 2 .... lot of times and hope that the number of steps was sufficient enough to avoid ALL the outliers ?
> 
> Regards,
> 
> Gwennaël
> 
> 
> Le 20/03/2014 14:15, PIKAL Petr a écrit :
>> Hi
>> 
>> I have a strong suspiction that you want to reinvent wheel.
>> 
>> does functions
>> ?chull (grDevices) and ?pip (splancs) do what you want?
>> 
>> Regards
>> Petr
>> 
>>> -----Original Message-----
>>> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
>>> project.org] On Behalf Of Gwennaël Bataille
>>> Sent: Thursday, March 20, 2014 9:55 AM
>>> To: r-help at r-project.org
>>> Subject: [R] How to make a code last until a condition is completed ?
>>> 
>>> # Dear all,
>>> 
>>> # I simulate individual paths in a landscape (let's say coordinates in
>>> x
>>> and y range
>>> # from -100 to 100 both) and would like to replace each individual
>>> going
>>> outside the
>>> # landscape by a new simulation... until none of them goes outside the
>>> landscape.
>>> 
>>> # For example, I simulate 100 coordinates :
>>> 
>>> # Step 1 : Simulate the individuals coordinates
>>> 
>>> paths_x<- rnorm(100)*100  # This is a simplification for the example
>>> paths_y<- rnorm(100)*100
>>> 
>>> # Step 2 : Detect individuals outside the landscape to simulate them
>>> again
>>> # The OUTSIDE variable tells if we need further simulations or not
>>> # The OUTSIDE_IND variable informs about which individuals are outside
>>> the landscape
>>> 
>>> IS_OUTSIDE<- c(-min(paths_x), max(paths_x), -min(paths_y),
>>> max(paths_y)) # this gives the absolute value of min and max
>>> if( any(IS_OUTSIDE>  100) ) { OUTSIDE<- TRUE } else { OUTSIDE<- FALSE
>>> }
>>> if(OUTSIDE == TRUE) { OUTSIDE_IND<- c(which(paths_x<  -100),
>>> which(paths_x>  100), which(paths_y<  - 100), which(paths_y>  100)) } #
>>> Identifies the outliers
>>> 
>>> # What I would like to do is :
>>> 
>>> if( OUTSIDE == TRUE ) {   # Go to step 1 again
>>> paths_x[ OUTSIDE_IND ]<- rnorm(100)[ length( OUTSIDE_IND ) ]*100
>>> paths_y[ OUTSIDE_IND ]<- rnorm(100)[ length( OUTSIDE_IND ) ]*100
>>> }   # And then, go to step 2 again :
>>> # are there some individuals outside the landscape again ? ->  if yes,
>>> go
>>> to step 1 untill none is left
>>> 
>>> else { # Go to step 3 }
>>> 
>>> # I could easily copy-paste steps 1 and 2 a lot of time, but I want to
>>> make sure all the individuals are OK,
>>> # that none remains outside the landscape "by chance"
>>> 
>>> # Thank you very much in advance for your help,
>>> 
>>> # Gwennaël Bataille
>>> 
>>> 
>>> --
>>> Gwennaël BATAILLE, PhD student - Teaching assistant
>>> 
>>> Earth and Life Institute
>>> Université Catholique de Louvain
>>> SST/ELI/ELIB
>>> Bâtiment Carnoy, c.145
>>> Croix du sud 4-5, bte L7.07.04
>>> 1348 Louvain-la-Neuve
>>> BELGIUM
>>> 
>>> ______________________________________________
>>> 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.
>> ________________________________
>> Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny pouze jeho adresátům.
>> Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze svého systému.
>> Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
>> Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či zpožděním přenosu e-mailu.
>> 
>> V případě, že je tento e-mail součástí obchodního jednání:
>> - vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
>> - a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce s dodatkem či odchylkou.
>> - trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným dosažením shody na všech jejích náležitostech.
>> - odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi či osobě jím zastoupené známá.
>> 
>> This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
>> If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
>> If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
>> The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.
>> 
>> In case that this e-mail forms part of business dealings:
>> - the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
>> - if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
>> - the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
>> - the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.
> 
> 
> -- 
> Gwennaël BATAILLE, PhD student - Teaching assistant
> 
> Earth and Life Institute
> Université Catholique de Louvain
> SST/ELI/ELIB
> Bâtiment Carnoy, c.145
> Croix du sud 4-5, bte L7.07.04
> 1348 Louvain-la-Neuve
> BELGIUM
> 
> ______________________________________________
> 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