R防止反向迭代的"for"循环

Ali*_*Ali 2 iteration for-loop r

请考虑以下代码:

foo = list("First List", 1, 2, 3)
bar = function(x) {
    cat("The list name is:", x[[1]], "\nThe items are:\n")
    for (i in 2:length(x))
        cat(x[[i]], "\n")
}
bar(foo)
Run Code Online (Sandbox Code Playgroud)

结果将是:

The list name is: First List 
The items are:
1 
2 
3 
Run Code Online (Sandbox Code Playgroud)

现在考虑传递一个没有项目但是名称的列表:

baz = list("Second List")
bar(baz)
Run Code Online (Sandbox Code Playgroud)

结果将是:

The list name is: Second List 
The items are:
Error in x[[i]] : subscript out of bounds
Run Code Online (Sandbox Code Playgroud)

该错误是因为2:length(x)将为c(2, 1)后一种情况产生一系列bar(baz),因此它尝试访问baz[2]并且它不存在.

如何for在R 中的循环中简单地防止这种不需要的反向迭代?

And*_*rie 9

seq_along有助于:

bar <- function(x) {
  cat("The list name is:", x[[1]], "\nThe items are:\n")
  for (i in seq_along(x[-1])) cat(x[[i+1]], "\n")   ### Edit ###
}
Run Code Online (Sandbox Code Playgroud)

结果:

bar(foo)
The list name is: First List 
The items are:
First List 
1 
2 
3 

bar(baz)
The list name is: Second List 
The items are:
Second List 
Run Code Online (Sandbox Code Playgroud)

当然,最好不要使用for循环,但不要使用循环lapply:

bar <- function(x) {
  cat("The list name is:", x[[1]], "\nThe items are:\n")
  lapply(x[-1],  function(xx)cat(xx, "\n"))
  invisible(NULL)
}

bar(foo)
The list name is: First List 
The items are:
1 
2 
3 

bar(baz)
The list name is: Second List 
The items are:
Run Code Online (Sandbox Code Playgroud)

  • 将`seq_along(x)`替换为`seq_along(x [-1])`和`x [[i]]`替换为`x [[i + 1]]`. (2认同)