Forest
Forest

Reputation: 721

R: convert list names to matrix entries

I have a list object that looks like this:

str(regul))
List of 656
 $ 10001    :List of 2
  ..$ tfmode    : Named num [1:168] 0.994 0.992 -0.743 0.906 0.683 ...
  .. ..- attr(*, "names")= chr [1:168] "22938" "5684" "9780" "11339" ...
  ..$ likelihood: num [1:168] 0.998 0.993 0.936 0.966 0.482 ...
 $ 10011    :List of 2
  ..$ tfmode    : Named num [1:88] 1 1 0.999 1 1 ...
  .. ..- attr(*, "names")= chr [1:88] "3035" "4695" "113829" "5201" ...
  ..$ likelihood: num [1:88] 1 1 1 1 1 ...

I want to create a 2-column matrix that looks like this:

head(newRegul)
      TF   Target
   10001   22938
   10001   5684
   10001   9780
   ...
   10011   3035
   10011   4695
   ...

So, there would be 168 rows wherein the first column is "10001" and the second column contains the names of the matching regul$tfmode, followed by 88 rows where column 1 consists of 10011 & column 2 consists of its matching regul$tfmode names, etc.

I've been trying to do this, using unlist() and string splitting, but have been running into a lot of problems. Is there some simple(ish) way to do this?

Thanks and sorry if this is a duplicate question. If it is, please post the link & I'll delete this post.

Upvotes: 1

Views: 193

Answers (1)

akrun
akrun

Reputation: 887641

We can use melt from library(reshape2)

library(reshape2)
melt(lapply(regul, function(x) names(x[[1]])))
#  value    L1
#1 22938 10001
#2  5564 10001
#3  1123 10011
#4  1533 10011

Or we can use stack in combination with transpose from library(purrr)

library(purrr)
library(dplyr)
transpose(regul) %>%
       .$tfmode %>%
        map(names) %>%
        stack
#  values   ind
#1  22938 10001
#2   5564 10001
#3   1123 10011
#4   1533 10011

data

 regul <- list(`10001`=list(tfmode= setNames(c(0.994, 
   0.992), c(22938, 5564)), likelihood=c(0.998, 0.834)),
 `10011`=list(tfmode=setNames(c(0.7, 0.3), c(1123, 
  1533)), likelihood= c(0.4, 0.3)))

Upvotes: 1

Related Questions