【发布时间】: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