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
If you look at the args for
sapply()
, you will see that the first three unnamed arguments given to it will be treated the input data (X
), the function to be applied (FUN
) and additional arguments to pass to that function (...
)So when you call
sapply(x,'[',"mpg")
on the list resulting from the split onmpg
, you are effectively calling the indexing operator[
on each element in the list, and passing the stringmpg
to it, e.g.:Finally, in the process of assembling the results back into a list, the names are lost, so you end up with: