我想了解在R中for循環的工作方式。我想出解決方案來解決我的問題,但留下了對其基本工作的懷疑。循環如何爲R中的向量工作?
在創建函數的過程中,我遇到了這個問題。問題在於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
這是一個有效的概念,我知道這是一個問題,如果你運行前兩個塊,它不會循環遍歷第一部分中的所有元素,但是工作得很好,直到它的某個索引。 – freetiger
你的第一個循環'for(我在temp_vector中)'循環了向量'temp_vector'的元素。然後你使用'i'來訪問你的矢量的一部分,例如這裏'!is.na(temp_vector [i])'。在第一次迭代中,一切都很好,因爲'i = 1',但是在第二次迭代中'i = NA',並且您多次使用'i'來訪問部分矢量,是否應該使用適當的索引。 – rhole
沒錯!謝謝!公認! – freetiger