我正在尝试理解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
答案 0 :(得分:2)
考虑以下示例:
> y <- c(2, 5, 3, 9, 8, 11, 6)
for
遍历您提供的矢量。在第一种情况下,您迭代向量y
的元素:
> for (val in y) {
+ print(val)
+ }
[1] 2
[1] 5
[1] 3
[1] 9
[1] 8
[1] 11
[1] 6
在第二种情况下,您正在迭代向量1:length(y)
的元素,这意味着c(1, 2, 3, 4, 5, 6, 7)
:
> for (val in 1:length(y)) {
+ print(val)
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
你在上面的代码中混淆了这一点。希望这能解决问题!
答案 1 :(得分:0)
您正在使用的for循环以这种方式工作(我将采用第一个变体,即变体-0)
这是正常的定义部分
y <- c(2,5,3,9,8,11,6)
count <- 0
以下是业务开始的地方:
for (val in y)
这里,val将包含向量y的值,它将在每次迭代中发生变化。
例如:
val for iteration 1: 2;
val for iteration 2: 5;
val for iteration 3: 3;
等等。
{
if(val %% 2 == 0)
count = count+1
}
print(count)
因此,这里,当val为偶数时,计数将递增,即迭代:1,5,7
因此,计数值为3。