I have successfully created a number of functions which contain code which draws a single polygon at a specific location. however, my attempts to create function for code which uses a loop to draw a sequence of polygon from left to right has resulted in only one polygon being drawn - either the first or the last. (I couldn't work out how to access reprex so I have pasted the code below.) The code below draws the fist polygon. There should be 10 in total.
when you hit return , you exit your function early with that single result that is returned.
if you are hand rolling loops and want the results of every step of the loop, you need to write code to accomodate that.
Here is an analogous example first of the sort of code you have shared, and second how it might be changed.
loopingfunction <- function(x) {
i <- 1
while (i <= length(x)) {
x2 <- x[i]*x[i]
return(x2)
i <- i +1
}
}
loopingfunction(3:1)
loopingfunction_2 <- function(x) {
i <- 1
result_vector <- numeric(length(x))
while (i <= length(x)) {
result_vector[i] <- x[i]*x[i]
i <- i +1
}
return(result_vector)
}
loopingfunction_2(3:1)
Thank you. I have only been using R for 3 weeks so my interpretation of your solution may be incorrect but it looks like you are adding a loop outside the original loop, Is that correct? What is the significance of the (3:1)?
3:1 has no significance its just a sequence of number 3 , 2, 1
There is only a single loop in both functions, the loop occurs within the curly braces of the while(){}
The point is not to 'return' from inside the loop. rather collect the information together, and returning happens at the end when a loop has finished.
As you are learning R from first principles, my best resource for education in that is the swirl package. swirl | Students (swirlstats.com)
Its a great course.
After completing the swirl course, you will also benefit greatly from the textbook 'R for Data Science' Welcome | R for Data Science (had.co.nz)
I looked closely at your suggestion in your first post but could not see how to incorporate it in my code. I understand the point you made in your second post and hopefully I will see the light in the morning. Thanks again.