2017-10-05 98 views
0

我是新來的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)) 
+2

建議的僞裝:[[\]和[[[]]之間的區別](https://stackoverflow.com/q/1169456/903061),儘管[如何在R中正確使用列表?](https://stackoverflow.com/q/2050790/90306)也是相關的。簡而言之,如果'x'是一個列表,那麼'x [[1]]'選擇'x'的第一個元素,而'x [1]'包含'x的第一個元素的子列表'。使用'help(「[[」)'作爲內置的幫助。 – Gregor

+0

哪個列表是雙括號引用的? – Aitch

+0

該函數返回'list(result,counter)'。所以'helper.call [[1]]'指的是'result'。 –

回答

0

在R中有兩種基本類型的對象:列表和向量。列表項可以是其他對象,矢量項通常是數字,字符串等。

要訪問列表中的項目,請使用雙括號[[]]。這將返回列表中該位置的對象。 所以

x <- 1:10 

X現在是一個整數向量

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

L是它的第一項是矢量x,其第二項是矢量並且其第三項是字符串列表「你好」。

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)