Secondly, lapply is the correct answer in this case. But there are many scenarios where a loop is needed, and this is a good question.
Lists of R need not be declared empty ahead of time, so the easiest way to do this is to simply “declare” RES as an empty list:
RES <- list() for (i in 1:1000) { RES[i] = kmeans(iris,i) }
R just extends the list for each iteration.
By the way, this works even for unclassified indexing:
newList <- list() newList[5] <- 100
displays a list with slots 1 through 4, created as NULL, and the number 100 in the fifth slot.
That’s all we can say that lists are very different animals in R than atomic vectors.
source share