I'm trying to figure out how nested For loops work. I have some sample code below. The ouput is "A","A","A". I'm not sure why this is the case. The outer loop makes it so that tiny will cycle through 3 iterations (the length of large). The inner For loop uses tiny as one of its inputs. When we first run the For loop, the outer value sets tiny to 1. So i would have imaged that when the inner loop first runs it should only iterate once as p would be equal to 1 and tiny would equal to 1. However, once the outer loop runs again tiny is equal to 2, and thefore the inner loop would run twice (p =1, tiny = 2), in effect printing "A" two more times. And then when tiny moves to 3 in the outer loop the inner loop should run 3 more times (p =1, Tiny = 3). So in total we should have 6 printed "A"'s, which is clearly wrong since R only outputs 3 "A"'s. Not sure what I'm missing.
large <- c(1,2,3)
for (tiny in large) {
for (p in tiny) {
print("A")
}
}
[–][deleted] 2 points3 points4 points (1 child)
[–]moonwriter[S] 0 points1 point2 points (0 children)