Jeremy K.
Jeremy K.

Reputation: 1792

`purrr:map()` to print items in a list and also their names

I've got a simple problem that I'd like to be able to use purrr::map() on.

I've got a list of named items (this example using the mtcars dataset):

var_labels <- list(cyl =  "Number of Cylinders",
                  disp = "Displacement")

I'm able to print all of the chr list items (printing is a simplification of my real problem):

print_label <- function(x){
  print(x)
}

map(var_labels, print_label)

Which gives:

>[1] "Number of Cylinders"
>[1] "Displacement"
>$cyl
>[1] "Number of Cylinders"
>
>$disp
>[1] "Displacement"

But I don't seem to be able to print the list items and their names:

print_item_and_name <- function(x){
  print(x)
  print(names(x))
}

map(var_labels, print_item_and_name)

which gives me NULLs:

>[1] "Number of Cylinders"
>NULL
>[1] "Displacement"
>NULL
>$cyl
>NULL

>$disp
>NULL

My real problem is not just printing the items and their names, but I suspect that if I can get a solution to this simplified step, I should be able to solve my real problem.

Desired output would be:

>[1] "Number of Cylinders"
>    "cyl"
>[1] "Displacement"
     "disp"

Upvotes: 3

Views: 960

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

map does not have access to names of the list. For that imap is used :

print_item_and_name <- function(x, y){
   print(x)
   print(y)
}

purrr::imap(var_labels, print_item_and_name)

You can also pass names separately and use map2 :

purrr::map2(var_labels, names(var_labels), print_item_and_name)

which is same as using mapply/Map in base.

Map(print_item_and_name, var_labels, names(var_labels))

Upvotes: 5

Related Questions