Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R How do I extract first row of each matrix within a list?

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

like image 344
shecode Avatar asked Aug 07 '14 09:08

shecode


People also ask

How do you select the first row of a matrix in R?

If you want to select all elements of a row or a column, no number is needed before or after the comma, respectively: my_matrix[,1] selects all elements of the first column. my_matrix[1,] selects all elements of the first row.

How do I extract the first element of 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).

How do I extract a row from a matrix in R?

R – Get Specific Row of Matrix To get a specific row of a matrix, specify the row number followed by a comma, in square brackets, after the matrix variable name.


2 Answers

Or,

lapply(mylist_1, `[`,1,)
lapply(mylist_1, `[`,2,)
like image 94
akrun Avatar answered Oct 12 '22 23:10

akrun


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,])
like image 42
talat Avatar answered Oct 12 '22 23:10

talat