私はRのベクトルのforループの働きを理解しようとしています。問題の解決法を考え出しましたが、その基本的な作業については疑問が残っていました。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ループのいくつかのバリエーションです。基本的にどのように動作するかを理解しようとしています。もしあなたがそれについていくらか光を当てることができれば助けになるだろう。ありがとう!あなたが提供するベクトルオーバー
> y <- c(2, 5, 3, 9, 8, 11, 6)
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
であると私は知っています最初の2つのチャンクを実行すると、最初の部分のすべての要素をループしていませんが、特定のインデックスまではうまく動作します。 – freetiger
最初のループ 'for(i in temp_vector)'は、ベクトル 'temp_vector'の要素をループします。次に、ベクトルの部分にアクセスするために 'i'を使います。ここには!is.na(temp_vector [i]) 'があります。最初の反復では、 'i = 1'なのですべてが正常ですが、2回目の反復' i = NA'では 'i'を数回使ってベクトルの部分にアクセスします。代わりに適切なインデックスを使うべきです。 – rhole
そうですよ!ありがとう!受け入れられる! – freetiger