双括号的使用不清楚

use of double brackets unclear

我是 R 的新手。正在阅读 Tilman Davies 的 R 书。提供了一个示例,说明如何使用外部定义的辅助函数,该函数顺便使用了双方括号 [[]]。请解释 helper.call[[1]] 和 helper.call[[2]] 的作用以及双括号的使用。

multiples_helper_ext <- function(x=foo,matrix.flags,mat=diag(2){
  indexes <- which(matrix.flags)
  counter <- 0
  result <- list()
  for(i in indexes){
    temp <- x[[i]]
    if(ncol(temp)==nrow(mat)){
      counter <- counter+1
      result[[counter]] <- temp%*%mat
    }
  }
  return(list(result,counter))
}

multiples4 <- function(x,mat=diag(2),str1="no valid matrices",str2=str1){
  matrix.flags <- sapply(x,FUN=is.matrix)

  if(!any(matrix.flags)){
    return(str1)
  }

  helper.call <- multiples_helper_ext(x,matrix.flags,mat=diag(2)
  result <- helper.call[[1]] #I dont understand this use of double bracket
  counter <- helper.call[[2]] #and here either

  if(counter==0){
    return(str2)
  } else {
    return(result)
  }
}
foo <- list(matrix(1:4,2,2),"not a matrix","definitely not a matrix",matrix(1:8,2,4),matrix(1:8,4,2))

语法 [[]] 用于 python 中的 list。您的 helper.call 是一个列表(resultcounter),因此 helper.cal[[1]] returns 是该列表的第一个元素 (result)。 看看这里:Understanding list indexing and bracket conventions in R

在 R 中有两种基本类型的对象:列表和向量。列表的项可以是其他对象,向量的项通常是数字、字符串等

要访问列表中的项目,请使用双括号 [[]]。这将返回列表中该位置的对象。 所以

x <- 1:10

x 现在是整数向量

L <- list( x, x, "hello" )

L 是一个列表,其第一项是向量 x,第二项是向量 x,第三项是字符串 "hello"。

L[[2]]

这会返回一个向量,1:10,它存储在 L 中的第 2 个位置。

L[2]

这有点令人困惑,但这会返回一个列表,其唯一项是 1:10,即它只包含 L[[2]].

在 R 中,当您想要 return 多个值时,通常使用列表来实现。所以,你可能会用

结束你的功能
f <- function() {
  return( list( result1="hello", result2=1:10) )
}
x = f()

现在您可以使用

访问两个结果
print( x[["result1"]] )
print( x[["result2"]] )

您还可以使用 ''$ 访问列表项,因此您可以编写

print( x$result1 )
print( x$result2 )