Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of matrices to a data.frame with row.names as names of list

Tags:

list

r

matrix

I have a list of matrices called list1 with the following structure:

$ENSLAFT00000000003
     start end
[1,]   360 360
[2,]   394 394

$ENSLAFT00000000011
     start end
[1,]    15  15

$ENSLAFT00000000020
     start end
[1,]    45  45

$ENSLAFT00000000023
     start end

$ENSLAFT00000000024
     start  end
[1,]    13   13
[2,]   369  369
[3,]   602  602
[4,]   775  775
[5,]   983  983
[6,]  1200 1200
[7,]  1491 1491

Some of the items are empty but I would like to transform this list into a data.frame with two columns and the following structure:

ID                         pos
ENSLAFT00000000003         360
ENSLAFT00000000003         394
ENSLAFT00000000011          15
ENSLAFT00000000020          45
ENSLAFT00000000024          13
ENSLAFT00000000024         369
ENSLAFT00000000024         602
ENSLAFT00000000024         775
ENSLAFT00000000024         983
ENSLAFT00000000024        1200
ENSLAFT00000000024        1491 

ENSLAFT00000000023 was omitted in the output as it was an empty matrix in the initial list.

I can somewhat get the desired structure but without keeping the rowname identity by using:

as.data.frame(do.call(rbind, e)[,1])

But I am still lacking to keep the rownames, which are needed.

Do you have any suggestions for doing this data transformation in R?

Best regards

like image 610
Emilio Mármol Sánchez Avatar asked Oct 28 '25 13:10

Emilio Mármol Sánchez


1 Answers

We extract the 'start' element by looping over the list and stack it to a two column data.frame

out <- stack(lapply(lst1, \(x) {
          st <- x[,"start"]
          if(length(st) == 0) st <- NA_real_
          st
            }))[2:1]
names(out) <- c("ID", "pos")
like image 115
akrun Avatar answered Oct 31 '25 02:10

akrun