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

Gwennaël Bataille gwennael.bataille at uclouvain.be
Thu Mar 20 09:55:15 CET 2014


# 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



More information about the R-help mailing list