我是新來的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'。 –