Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subset a vector inside list of list

Tags:

list

r

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?

like image 812
scamander Avatar asked Aug 08 '19 03:08

scamander


People also ask

How do you subset elements in a list?

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.

How do you subset vectors?

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.

How do I extract a list from a list in R?

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).


3 Answers

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 recursive 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.

like image 140
thelatemail Avatar answered Oct 21 '22 00:10

thelatemail


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)
like image 40
Ronak Shah Avatar answered Oct 21 '22 01:10

Ronak Shah


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
like image 34
Lala La Avatar answered Oct 21 '22 01:10

Lala La