# using `i` directly
x <- seq(10)
for(i in x){
print(2^i)
}[1] 2
[1] 4
[1] 8
[1] 16
[1] 32
[1] 64
[1] 128
[1] 256
[1] 512
[1] 1024
for() every element of e.g. a vectori) can be used directly# using `i` directly
x <- seq(10)
for(i in x){
print(2^i)
}[1] 2
[1] 4
[1] 8
[1] 16
[1] 32
[1] 64
[1] 128
[1] 256
[1] 512
[1] 1024
x <- 2:20
# using `i` as an index
for(i in 1:length(x)){
print(x[i]^2)
}[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
[1] 49
[1] 64
[1] 81
[1] 100
[1] 121
[1] 144
[1] 169
[1] 196
[1] 225
[1] 256
[1] 289
[1] 324
[1] 361
[1] 400
# using `i` as an index
for(i in c(2, 4, 11, 7)){
print(x[i]^2)
}[1] 9
[1] 25
[1] 144
[1] 64
Why is there an NA output in the second example?
x <- 1:10
for(i in x){
result <- x[i]^2
}
result[1] 100
Why is the result 100? What did you expect?
If you want to save the result of the loop, you have to assign the output to e.g. element of a vector.
x <- 1:10
result <- c()
for(i in x){
result[i] <- x[i]^2
}
result [1] 1 4 9 16 25 36 49 64 81 100