5

Say I have a list called mylist_1 with 2 matrices:

mylist_1

$region_1           
users   50  20  30
revenue 10000   3500    4000

$red            
users   20  20  60
revenue 5000    4000    10000

How do I extract the first row of each matrix into its own matrix?

i.e. output (first column here are rownames):

region_1    50  20  30
region_2    20  20  60

or the second row of each matrix?

region_1    10000   3500    4000
region_2    5000    4000    10000

Is there a way to reference the list/matrices to do this?

Thanks

shecode
  • 1,716
  • 6
  • 32
  • 50

2 Answers2

12

Or,

lapply(mylist_1, `[`,1,)
lapply(mylist_1, `[`,2,)
akrun
  • 874,273
  • 37
  • 540
  • 662
7

To extract the first row per matrix you can use:

lapply(mylist1, head, 1)

Or, if you want to rbind them:

do.call(rbind, lapply(lst, head, 1))

Or for (only) the second row per matrix:

lapply(lst, function(x) x[2,])
talat
  • 68,970
  • 21
  • 126
  • 157