# Storing iterations in a while loop as another object which should be a vector called 'position'

I need to store the plane's elevation every period in a vector called 'position'.
the code below shows how the plane's elevation starts at 5 and with every iteration the
plane goes up or down by one unit. Eventually, the plane will hit elevation zero, at which point the loop should stop.
the object iterator is 'time' in the code.
My task is to store the plane's elevation every period in a vector called 'position'

``````max_period <- 100
elevation <- 5
time <- 0
while(elevation > 0){
elevation <- elevation + sample(c(-1,1), 1)
time <- time + 1
print(paste("Current time:", time, " Elevation: ", elevation))
if (time > max_period && elevation > 0) {
break
}
}

if (elevation == 0) {
print(paste("CRASH! You lasted", time, "periods."))
} else {
print(paste("NOT CRASHED! You lasted", time, "periods.", "Elevation", elevation))
}
``````

Hi @clarisse_vaz. Do you mean something as follow?

``````max_period <- 100
elevation <- 5
time <- 0
position <- c()
while(elevation > 0){
elevation <- elevation + sample(c(-1,1), 1)
time <- time + 1
position <- c(position, elevation)
print(paste("Current time:", time, " Elevation: ", elevation))
if (time > max_period && elevation > 0) {
break
}
}
#> [1] "Current time: 1  Elevation:  6"
#> [1] "Current time: 2  Elevation:  5"
#> [1] "Current time: 3  Elevation:  6"
#> [1] "Current time: 4  Elevation:  5"
#> [1] "Current time: 5  Elevation:  6"
#> [1] "Current time: 6  Elevation:  5"
#> [1] "Current time: 7  Elevation:  4"
#> [1] "Current time: 8  Elevation:  3"
#> [1] "Current time: 9  Elevation:  2"
#> [1] "Current time: 10  Elevation:  3"
#> [1] "Current time: 11  Elevation:  2"
#> [1] "Current time: 12  Elevation:  3"
#> [1] "Current time: 13  Elevation:  2"
#> [1] "Current time: 14  Elevation:  1"
#> [1] "Current time: 15  Elevation:  2"
#> [1] "Current time: 16  Elevation:  1"
#> [1] "Current time: 17  Elevation:  0"

if (elevation == 0) {
print(paste("CRASH! You lasted", time, "periods."))
} else {
print(paste("NOT CRASHED! You lasted", time, "periods.", "Elevation", elevation))
}
#> [1] "CRASH! You lasted 17 periods."

position
#>  [1] 6 5 6 5 6 5 4 3 2 3 2 3 2 1 2 1 0
``````

Created on 2020-02-26 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.