littleworth
littleworth

Reputation: 5169

How to access list names through lapply for a function

I have the following named list:

all_gene_list <- list(`1` = c(
  "0610005C13Rik", "0610007N19Rik", "0610007P14Rik",
  "0610008F07Rik", "0610009B14Rik"
), `2` = c(
  "0610009B22Rik", "0610009D07Rik",
  "0610009E02Rik", "0610009L18Rik", "0610009O20Rik"
), `3` = c(
  "0610010F05Rik",
  "0610010K14Rik", "0610011F06Rik", "0610012D04Rik", "0610012H03Rik"
))

And I have a function that tries to capture the name of each list:

make_rds <- function (glist = NULL) {
  x <- names(glist)
  cat("List id is:", x)

}

list_out <- lapply(all_genes_list, make_rds)

I expect it to print:

List id is: 1
List id is: 2
List id is: 3

But it doesn't. What's the right way to do it?

Upvotes: 0

Views: 662

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389235

In cases when you want to access names as well as contents of the list we can use Map/mapply instead. We can write a function

make_rds <- function (data, glist = NULL) {
   paste("List id is:", glist)
}

So we have data in make_rds function to access the content and glist to access name.

Map(make_rds, all_gene_list, names(all_gene_list))

#$`1`
#[1] "List id is: 1"

#$`2`
#[1] "List id is: 2"

#$`3`
#[1] "List id is: 3"

If you are into tidyverse, we can use map2 similarly

purrr::map2(all_gene_list, names(all_gene_list), make_rds)

Or imap where you don't need to pass names explicitly.

purrr::imap(all_gene_list, make_rds)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522626

What would be wrong with just using apply over the vector of list names:

list_out <- lapply(names(all_genes_list), function(x) cat("List id is:", x))

Of course, this assumes that you really want a list output from a vector of names input. I would probably use sapply here instead of lapply.

Edit:

If you want a list with the same original content but the new names, then try:

all_genes_list_new = duplicate(all_genes_list)
names(all_genes_list_new) <- paste("List id is:", names(all_genes_list))

Upvotes: 3

Related Questions