首页 > 解决方案 > map over list, get item name and content

问题描述

my_dfs <- list(
  mtcars = mtcars,
  diamonds = diamonds
)
map(.x = my_dfs, ~ print(.x %>% str)) # OK

But if I also want to access the name of the item in the list being printed, how can I do that?

map(.x = my_dfs, ~ print(.id)) # found a reference to .id in the docs.
Error in print(.id) : object '.id' not found

Better yet, I would like both in one call to map, e.g.

map(.x = my_dfs, ~ print('About to print str of ' [somehow get list item name here] .x %>% str))

标签: rpurrr

解决方案


使用imap(). 内容将由 引用.x,名称由.y

z <- list(x = "whats in x",
          y = "whats in y")

imap(z, ~ paste(.y, "has contents:", .x))
# $x
# [1] "x has contents: whats in x"
# 
# $y
# [1] "y has contents: whats in y"

推荐阅读