到目前为止,我的 for 循环虽然使用了向量,但工作正常:
foo = c("one","two","three")
for (bar in 1:length(foo)) {
print(bar)
}
#[1] 1
#[1] 2
#[1] 3
Run Code Online (Sandbox Code Playgroud)
但是,我注意到即使向量为空也会访问循环:
foo = c()
for (bar in 1:length(foo)) {
print(bar)
}
#[1] 1
#[1] 0
Run Code Online (Sandbox Code Playgroud)
当然,我可以使用 IF 语句(if (length(foo)!=0)),但我确信有更好的方法来做到这一点。
也许我有一个过于“pythonic”的策略,因为在那里我不会有问题
foo = []
for bar in foo:
print(bar)
Run Code Online (Sandbox Code Playgroud)
如果我的向量为空,防止访问 for 循环的最佳方法是什么?
是的,更好的方法是使用seq_along循环遍历向量。
foo = c("one","two","three")
for (bar in seq_along(foo)) {
print(bar)
}
#[1] 1
#[1] 2
#[1] 3
foo = c()
for (bar in seq_along(foo)) {
print(bar)
}
#Prints nothing
Run Code Online (Sandbox Code Playgroud)
基于 jogos 注释的编辑:Indexing可用于直接访问向量元素:
foo = c("one","two","three")
for (bar in foo) {
print(bar)
}
#[1] "one"
#[1] "two"
#[1] "three"
foo = c()
for (bar in foo) {
print(bar)
}
#Prints nothing
Run Code Online (Sandbox Code Playgroud)