# using `i` directly
<- seq(10)
x
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
<- seq(10)
x
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
<- 2:20
x
# 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?
<- 1:10
x for(i in x){
<- x[i]^2
result
}
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.
<- 1:10
x <- c()
result
for(i in x){
<- x[i]^2
result[i]
}
result
[1] 1 4 9 16 25 36 49 64 81 100