r - 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))
解决方案
使用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"
推荐阅读
- sapui5 - SAPUI5 应用程序中的 JQuery 日期滑块
- jquery - 隐藏除当前弹出窗口之外的所有弹出窗口?
- php - 从程序将数据保存或存储在数据库中
- flutter - Flutter ListWheelScrollView
- android - 从与 FileProvider 共享大 pdf 文件的电子邮件客户端返回后,onCreate 被调用
- html - div 被放在上面的 div 中
- jsp - 为什么会话在我的 JSP 页面中返回 null?
- powershell - CSV 为空以导出广告用户的自定义属性
- runtime-error - 打开 SAP 时出现“nwbc.exe 已停止工作”错误
- c# - 在图片框中查找和显示图像