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

R language: why i can get the below outcome like this by Sapply function?

 x<- split(mtcars,mtcars$cyl)
 sapply(x,'[',"mpg")

"From the above code, could someone explain to me why I can get the following outcome and why putting '[' in the sapply can get the following outcome?"

$`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

如果您查看 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’.

因此,当您在 mpg 拆分后的列表上调用 sapply(x,'[',"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