我是新来的R.阅读由蒂尔曼戴维斯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))
建议的伪装:[[\]和[[[]]之间的区别](https://stackoverflow.com/q/1169456/903061),尽管[如何在R中正确使用列表?](https://stackoverflow.com/q/2050790/90306)也是相关的。简而言之,如果'x'是一个列表,那么'x [[1]]'选择'x'的第一个元素,而'x [1]'包含'x的第一个元素的子列表'。使用'help(“[[”)'作为内置的帮助。 – Gregor
哪个列表是双括号引用的? – Aitch
该函数返回'list(result,counter)'。所以'helper.call [[1]]'指的是'result'。 –