代码之家  ›  专栏  ›  技术社区  ›  Huang

R语言:为什么我可以通过Sapply函数得到如下结果?

  •  0
  • Huang  · 技术社区  · 8 年前
     x<- split(mtcars,mtcars$cyl)
     sapply(x,'[',"mpg")
    

    “从上面的代码中,有人能向我解释为什么我能得到以下结果以及为什么 '[' sapply 可以得到以下结果吗?"

    $`4.mpg`
     [1] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26.0 30.4 21.4
    
    $`6.mpg`
    [1] 21.0 21.0 21.4 18.1 19.2 17.8 19.7
    
    $`8.mpg`
     [1] 18.7 14.3 16.4 17.3 15.2 10.4 10.4 14.7 15.5 15.2 13.3 19.2 15.8 15.0
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   Keith Hughitt rjhcnf    8 年前

    如果您查看参数 sapply() ,您将看到前三个未命名的参数将被视为输入数据( X ),要应用的函数( FUN )以及传递给该函数的其他参数( ... )

    > args('sapply')
    function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE) 
    
    > help('sapply')
    ...
         X: a vector (atomic or list) or an ‘expression’ object.  Other
              objects (including classed objects) will be coerced by
              ‘base::as.list’.
    
         FUN: the function to be applied to each element of ‘X’: see
              ‘Details’.  In the case of functions like ‘+’, ‘%*%’, the
              function name must be backquoted or quoted.
    
         ...: optional arguments to ‘FUN’.
    

    所以当你打电话的时候 sapply(x,'[',"mpg") 在由上的拆分产生的列表上 mpg ,您正在有效地调用索引运算符 [ 在列表中的每个元素上,并传递字符串 mpg 例如:

    x$`4`['mpg']
                    mpg
    Datsun 710     22.8
    Merc 240D      24.4
    Merc 230       22.8
    Fiat 128       32.4
    Honda Civic    30.4
    Toyota Corolla 33.9
    Toyota Corona  21.5
    Fiat X1-9      27.3
    Porsche 914-2  26.0
    Lotus Europa   30.4
    Volvo 142E     21.4
    

    最后,在将结果组合回列表的过程中,名称将丢失,因此您将得到:

    $`4.mpg`
     [1] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26.0 30.4 21.4