r - 从嵌套列表中提取具有特定名称的所有元素
问题描述
我有一些存档的 Slack 数据,我正在尝试获取一些关键消息属性。我通过愚蠢地展平整个列表,获得一个 data.frame 或 tibble 列表嵌套在某些单元格中来做到这一点。随着这个数据集变得越来越大,我想更巧妙地从这个列表中挑选元素,这样当这个缓存变大时,就不需要永远用我想要的元素创建 data.frame 或 tibble。
我试图将下面名为“type”的所有内容拉入向量或平面列表中的示例,我可以将其作为数据框变量拉入。为方便起见,我命名了文件夹和消息级别。任何人都有可以提供帮助的模型代码?
library(tidyverse)
l <- list(folder_1 = list(
`msg_1-1` = list(type = "message",
subtype = "channel_join",
ts = "1585771048.000200",
user = "UFUNNF8MA",
text = "<@UFUNNF8MA> has joined the channel"),
`msg_1-2` = list(type = "message",
subtype = "channel_purpose",
ts = "1585771049.000300",
user = "UNFUNQ8MA",
text = "<@UNFUNQ8MA> set the channel purpose: Talk about xyz")),
folder_2 = list(
`msg_2-1` = list(type = "message",
subtype = "channel_join",
ts = "1585771120.000200",
user = "UQKUNF8MA",
text = "<@UQKUNF8MA> has joined the channel"))
)
# gets a specific element
print(l[[1]][[1]][["type"]])
# tried to get all elements named "type", but am not at the right list level to do so
print(purrr::map(l, "type"))
解决方案
正如OP所提到的,这可以解决问题:
#Code
unlist(l)[grepl('.type',names(unlist(l)),fixed=T)]
输出:
folder_1.msg_1-1.type folder_1.msg_1-2.type folder_2.msg_2-1.type
"message" "message" "message"
另一个选择是(非常感谢@Abdessabour Mtk)
#Code1
purrr::map(l, ~ purrr::map(.x, "type"))
推荐阅读
- javascript - 在弹出窗口中实施身份验证时,快速会话 cookie 过期
- c - 动态链接库相互依赖时的链接顺序问题
- php - 在查询 Eloquent 字段中添加结果子查询
- rust - rust 按顺序组合相似的值
- c++ - 字符串:删除字符并将数字分成块
- python-3.x - 如何使用 Python Pandas 和 mysqlalchemy 更改表
- c++ - 使用 std::thread 从 TCP 套接字发送和接收数据
- typescript - lodash - 使用 typescript 对数组进行分组和填充
- react-native - 无法读取未定义的属性“oneOf”
- sql - 查询对象的jsonb列总和