I have the following list of list:
foo <- list(a = list(x = 1:10, y = 11:25), b = list(x = 1:10, y = 100:110))
It looks like this:
> foo
$a
$a$x
[1] 1 2 3 4 5 6 7 8 9 10
$a$y
[1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
$b
$b$x
[1] 1 2 3 4 5 6 7 8 9 10
$b$y
[1] 100 101 102 103 104 105 106 107 108 109 110
What I want to do is to only pick first 3 of the list yielding:
$a
$a$x
[1] 1 2 3
$a$y
[1] 11 12 13
$b
$b$x
[1] 1 2 3
$b$y
[1] 100 101 102
How can I achieve that?
To subset these sub-elements we can use sapply function and use c to subset the number of corresponding sub-elements. For example, if we have a list that contains five elements and each of those elements have ten sub-elements then we can extract 1, 2, 3 etc elements from sub-elements.
The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.
To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).
A wild ?rapply
appears:
rapply(foo, f=head, n=3, how="list")
#$a
#$a$x
#[1] 1 2 3
#
#$a$y
#[1] 11 12 13
#
#
#$b
#$b$x
#[1] 1 2 3
#
#$b$y
#[1] 100 101 102
This is a r
ecursive apply
which will go through each list until a non-list is found and then apply a f=
unction. The how="list"
argument just ensures that you get the same list
structure back again.
Use nested lapply
lapply(foo, lapply, `[`, 1:3)
#$a
#$a$x
#[1] 1 2 3
#$a$y
#[1] 11 12 13
#$b
#$b$x
#[1] 1 2 3
#$b$y
#[1] 100 101 102
Or use head
lapply(foo, lapply, head, 3)
library(purrr)
foo %>% map_depth(2,head,3)
#$a
#$a$x
#[1] 1 2 3
#
#$a$y
#[1] 11 12 13
#
#
#$b
#$b$x
#[1] 1 2 3
#
#$b$y
#[1] 100 101 102
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With