【发布时间】:2016-04-08 14:40:56
【问题描述】:
我试图了解 R 中向量的 for 循环的工作原理。我找到了解决问题的方法,但对其基本工作原理存有疑问。
在创建函数的过程中,我遇到了这个问题。问题是 for 循环正在遍历向量的元素,但直到某个索引。
## the output is partially complete, seems like it didn't loop through all the values however the loop counter is perfect
temp_vector<- c(1, NA,Inf, NaN,3,2,4,6,4,6,7,3,2,5,NaN, NA, 3,3,NaN, Inf, Inf, NaN, NA, 3,5,6,7)
ctr<- 0
for(i in temp_vector){
temp_vector[i]<- ifelse((!is.na(temp_vector[i])) & (!is.infinite(temp_vector[i])), temp_vector[i], 0 )
## replace the element of vector by 0 if they are Inf or NA or NaN
ctr<- ctr+1
}
temp_vector
print(ctr)
# output
> temp_vector
[1] 1 0 0 0 3 2 4 6 4 6 7 3 2 5 NaN NA 3 3 NaN Inf Inf NaN NA 3 5 6 7
> print(ctr)
[1] 27
## this is generating correct output
temp_vector<- c(1, NA,Inf, NaN,3,2,4,6,4,6,7,3,2,5,NaN, NA, 3,3,NaN, Inf, Inf, NaN, NA, 3,5,6,7)
for(i in 1:length(temp_vector)){
temp_vector[i]<- ifelse((!is.na(temp_vector[i])) & (!is.infinite(temp_vector[i])), temp_vector[i], 0 )
## replace the element of vector by 0 if they are Inf or NA or NaN
}
temp_vector
# output
> temp_vector
[1] 1 0 0 0 3 2 4 6 4 6 7 3 2 5 0 0 3 3 0 0 0 0 0 3 5 6 7
以下是我尝试过的几个 for 循环变体,它们产生不同的输出,我试图了解它的基本工作原理。如果您能对此有所了解,那将很有帮助。谢谢!
## variant-0
y <- c(2,5,3,9,8,11,6)
count <- 0
for (val in y) {
if(val %% 2 == 0)
count = count+1
}
print(count)
# output
[1] 3
## variant-1
x<- c(2,4,6,4,6,7,3,2,5,6)
for(i in x){
x[i]<- ifelse(x[i]==6, NaN, x[i])
}
x
# output, Last element of the vector is not a NaN
[1] 2 4 NaN 4 NaN 7 3 2 5 6
## variant-2
x<- c(2,4,6,4,6,7,3,2,5,6)
ctr<- 0
for(i in x){
x[i]<- ifelse(x[i]==6, NaN, x[i])
ctr<- ctr+1
}
x
print(ctr)
# output, Note: Last element of the vector is not a NaN
> x
[1] 2 4 NaN 4 NaN 7 3 2 5 6
> print(ctr)
[1] 10
## variant-3
x<- c(2,4,6,4,6,7,3,2,5,6)
ctr<- 0
for(i in x){
x[ctr]<- ifelse(x[ctr]==6, NaN, x[ctr])
ctr<- ctr+1
}
x
print(ctr)
# output. Note: the counter is perfect
> x
[1] 2 4 NaN 4 NaN 7 3 2 5 6
> print(ctr)
[1] 10
## variant-4
x<- c(2,4,6,4,6,7,3,2,5,6)
ctr<- 0
for(i in x){
i<- ifelse(i==6, NaN, i)
ctr<- ctr+1
}
x
print(ctr)
# output
> x
[1] 2 4 6 4 6 7 3 2 5 6
> print(ctr)
[1] 10
【问题讨论】: