R:带有冒号运算符和空向量长度的 For 循环

Luk*_*ber 2 for-loop r

到目前为止,我的 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 循环的最佳方法是什么?

Ron*_*hah 5

是的,更好的方法是使用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)

  • @NelsonGon `seq_along` 在长度上循环。由于长度为 0,因此不会打印任何内容,而 `1:length` 创建一个从 1 到 `foo` 的 `length` 的序列,该序列为 0,因此最终它创建为序列 `1:0`。 (3认同)