代码之家  ›  专栏  ›  技术社区  ›  Gavin Simpson

如何正确使用`[` with(l_s)apply从矩阵列表中选择特定列?

r
  •  28
  • Gavin Simpson  · 技术社区  · 14 年前

    考虑下面的情况,我在对象中有一个n个矩阵的列表(在下面的示例中,这只是一个虚拟数据)。 myList

    mat <- matrix(1:12, ncol = 3)
    myList <- list(mat1 = mat, mat2 = mat, mat3 = mat, mat4 = mat)
    

    我想从每个矩阵中选择一个特定的列,并对它做些什么。这将得到每个矩阵的第一列,并将其作为矩阵返回( lapply() 也可以给我一份清单。

    sapply(myList, function(x) x[, 1])
    

    我不能做的就是利用 [ 直接作为我的函数 sapply() LAPP() 咒语。 ?'[' 告诉我我需要提供论据 j 作为列标识符。我做错了什么,这不管用?

    > lapply(myList, `[`, j = 1)
    $mat1
    [1] 1
    
    $mat2
    [1] 1
    
    $mat3
    [1] 1
    
    $mat4
    [1] 1
    

    我期望的是:

    $mat1
    [1] 1 2 3 4
    
    $mat2
    [1] 1 2 3 4
    
    $mat3
    [1] 1 2 3 4
    
    $mat4
    [1] 1 2 3 4
    

    我怀疑我弄错了 [ 方法,但我不知道为什么?思想?

    3 回复  |  直到 14 年前
        1
  •  23
  •   Richie Cotton Joris Meys    14 年前

    [ lapply(myList, `[`, i =, j = 1)

        2
  •  13
  •   Gavin Simpson    14 年前

    lapply(myList, `[`, , 1)
    

    mat[ ,1] j

    ?'['

    Argument matching:
    
         Note that these operations do not match their index arguments in
         the standard way: argument names are ignored and positional
         matching only is used.  So ‘m[j=2,i=1]’ is equivalent to ‘m[2,1]’
         and *not* to ‘m[1,2]’.
    

        3
  •  4
  •   Joshua Ulrich    14 年前

    [ .Primitive j [.matrix

    > `[`
    .Primitive("[")
    > args(`[`)
    NULL
    > methods(`[`)
     [1] [.acf*            [.AsIs            [.bibentry*       [.data.frame     
     [5] [.Date            [.difftime        [.factor          [.formula*       
     [9] [.getAnywhere*    [.hexmode         [.listof          [.noquote        
    [13] [.numeric_version [.octmode         [.person*         [.POSIXct        
    [17] [.POSIXlt         [.raster*         [.roman*          [.SavedPlots*    
    [21] [.simple.list     [.terms*          [.ts*             [.tskernel*