对于R中的向量,for循环是如何工作的?

对于R中的向量,for循环是如何工作的?,r,for-loop,vector,R,For Loop,Vector,我试图理解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,

我试图理解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
##输出部分完成,似乎没有循环通过所有值,但循环计数器是完美的

温度向量考虑以下示例:

> y <- c(2, 5, 3, 9, 8, 11, 6)
在第二种情况下,您迭代向量
1:length(y)
,意思是
c(1,2,3,4,5,6,7)


你在上面的代码中把这个混在一起了。希望这能把事情弄清楚

您正在使用的for循环是这样工作的(我将使用第一个变量,即variant-0)

这是正常的定义部分

y <- c(2,5,3,9,8,11,6)
count <- 0
这里,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


所以,count的值是3。

这是一个有效的概念,我知道这一点,但如果你运行前两个块,它不会在第一部分中的所有元素之间循环,但是在它的某个索引之前工作良好。你的第一个循环
for(I in temp_vector)
循环向量
temp_vector
的元素。然后您将使用
i
访问向量的部分,例如此处
!is.na(温度向量[i])
。在第一次迭代中,一切都很好,因为
i=1
,但在第二次迭代中
i=NA
,您多次使用
i
访问向量的部分,如果您应该使用适当的索引。
y <- c(2,5,3,9,8,11,6)
count <- 0
for (val in 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)