【发布时间】:2022-01-11 08:58:20
【问题描述】:
我有一个基本的 while 和 for 循环,我遍历数据帧中的一些起始值和结束值,然后遍历一个列表并获取(子字符串)一些值。
以下代码的问题在于它添加了很多 NA 行,我不明白为什么以及如何。
我有一个 if,它查看 GREPL-找到“TRACK 2 DATA:”,如果是,则在数据框中添加一行。我没有添加 NA 值的 else 。所以在我的理解中,如果 Block 为假,迭代应该继续而不是向数据框添加值?
可能出了什么问题?
i=1
fundi <- nrow(find_txn) #get the last record
while(i <=fundi) { # Start while-loop until END OF records
nga <- find_txn[i,1] #FRom record
ne <- find_txn[i,3] #to Records
for (j in nga:ne){ #For J in from:to
if(grepl("TRACK 2 DATA: ",linn[j])) { #If track data found do something
gather_txn[j,1] <- j # add a record for iteration number
gather_txn[j,2] <- substr(linn[j],1,9) #get some substrings
gather_txn[j,3] <- substr(linn[j],34,39) #get some substrings
}
}
i <- i + 1
}
【问题讨论】:
-
我认为您的索引可能有问题。 I
ve expected a global counting variable to increase the index for every added row, e.g.count count <- count + 1 用于增加循环 if(...)==T。然后应该使用gather_txn[count, 1]等等。如果您提供一个最小的可重现示例,我可以为您提供代码作为解决方案。 -
#JKupzig 感谢您的帮助。我解决了
-
为什么外循环是
while循环而不是for循环? -
@KonradRudolph 无缘无故,它也可以写在 for 循环中。
-
是的,使用
for循环会简化代码,即使只是轻微的。从长远来看,编写尽可能简单的代码会带来巨大的收益,因为复杂性和看似很小的复杂性加在一起会使代码更加更难理解。
标签: r loops for-loop while-loop