【问题标题】:use of double brackets unclear双括号的使用不清楚
【发布时间】:2018-03-17 14:48:32
【问题描述】:

我是 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))

【问题讨论】:

  • 建议的欺骗:Difference between [] and [[]]?,尽管How to correctly use lists in R? 也是相关的。简而言之,如果x 是一个列表,那么x[[1]] 选择x 的第一个元素,而x[1] 是一个包含x 的第一个元素的子列表(仍然是一个列表!)。使用help("[[") 获取内置帮助。
  • 双括号引用的是哪个列表?
  • 函数返回list(result,counter)。所以helper.call[[1]] 指的是result
  • helper.call[[1]] 索引列表helper.call
  • @RuiBarradas 哦,现在我看到辅助函数实际上返回了一个列表,并且 multiples4 使用 helper.call[[1]] 和 helper.call[[2]] 引用了其中的元素。如果您将您的标记为答案,我会检查它。谢谢。

标签: r square-bracket


【解决方案1】:

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

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

x <- 1:10

x 现在是整数向量

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

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

L[[2]]

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

L[2]

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

在 R 中,当您想要返回多个值时,通常使用列表来执行此操作。所以,你可以用

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

现在您可以使用

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

您也可以使用 ''$ 访问列表中的项目,因此您可以编写

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

【讨论】:

    【解决方案2】:

    [[]] 语法在 python 中用于list。你的helper.call 是一个列表(resultcounter),所以helper.cal[[1]] 返回这个列表的第一个元素(result)。 看看这里:Understanding list indexing and bracket conventions in R

    【讨论】:

    • 感谢 ZiGaelle 和 Rui Barradas
    猜你喜欢
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多