2017-10-05 53 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)