提问人:Xavier 提问时间:9/28/2023 最后编辑:AkselAXavier 更新时间:9/28/2023 访问量:51
如何在深度为 5 的 R 中设置嵌套列表的名称
How to Set Names for Nested Lists in R of Depth 5
问:
我正在 R 中使用深度嵌套的列表结构,并且无法为深度为 5 的列表设置名称。我已经设法为深度为 4 的列表做到了这一点,但我不确定如何进一步进行。以下是我试图实现的目标的可重复示例:
library(tidyverse)
# Create fake data
set.seed(1234)
data <- tibble(
category1 = rep(letters[1:4], each = 25),
category2 = sample(letters[5:9], size = 100, replace = T),
category3 = sample(letters[10:14], size = 100, replace = T),
some_variable = rnorm(100)
)
# Create the first named list of tibbles with assigned names (depth = 3)
nested_data1 <- data %>%
nest(.by = category1) %>%
pull(data) %>%
setNames(unique(data$category1))
# Create a list of vectors of names for layer 3
category2_by_category1 <- nested_data1 %>%
map(~pull(., "category2")) %>%
map(~unique(.))
# Create the second list of tibbles with assigned names (depth = 4)
nested_data2 <- nested_data1 %>%
map(~nest(., .by = "category2")) %>%
map(~pull(., data)) %>%
map2(category2_by_category1, ~set_names(.x, .y))
# Create a list of lists of vectors of names for layer 4
category3_by_category2_by_category1 <- nested_data2 %>%
map_depth(2, ~ pull(., "category3")) %>%
map_depth(2, ~ unique(.))
# Create the third list of tibbles without assigned names (depth = 5)
nested_data3 <- nested_data2 %>%
map_depth(2, ~ nest(., .by = "category3")) %>%
map_depth(2, ~ pull(., data))
# This line is the problem
map2(nested_data3, category3_by_category2_by_category1, ~map_depth(2, ~set_names(.x, .y)))
我想将最里面列表的名称设置为深度 3 中列出的元素。但是,我不确定该怎么做。category3_by_category2_by_category1
最后一行代码是我根据 acylam 对这个问题的回答做出的最佳尝试
这是我尝试运行最后一行代码时收到的错误消息:
Error in `map2()`:
ℹ In index: 1.
ℹ With name: a.
Caused by error in `map_depth()`:
! `depth` must be a whole number, not a <formula> object.
Run `rlang::last_trace()` to see where the error occurred.
感谢您的帮助!
答: 暂无答案
评论
map2(nested_data3, category3_by_category2_by_category1, \(x,y) (map_depth(x,2,\(x)(SetNames(x,pluck(y,1))))))