【发布时间】:2019-01-07 07:40:02
【问题描述】:
我的输出如下所示:
test_list <- list(list(x = c(10, 101, 3), y = c(9, 12, 11)),
list(x = c(10, 133, 4), y = c(9, 15, 13)),
list(x = c(10, 101, 90), y = c(9, 18, 11)),
list(x = c(10, 101, 1), y = c(9, 10, 15)))
我想选择和修改子列表 x 和 y 的特定元素。例如,我想用向量中的数字或从函数生成的数字替换 x 的最后一个元素 - 即;将向量 z <- c(10, 50, 6, 12) 映射到子列表 x 的最后一个元素上,得到:
test_list_1 <- list(list(x = c(10, 101, 10), y = c(9, 12, 11)),
list(x = c(10, 133, 50), y = c(9, 15, 13)),
list(x = c(10, 101, 6), y = c(9, 18, 11)),
list(x = c(10, 101, 12), y = c(9, 10, 15)))
或诸如rnorm(1)之类的函数覆盖每个子列表 x 的最后一个元素,以产生以下输出:
test_list_2 <- list(list(x = c(10, 101, rnorm(1)), y = c(9, 12, 11)),
list(x = c(10, 133, rnorm(1)), y = c(9, 15, 13)),
list(x = c(10, 101, rnorm(1)), y = c(9, 18, 11)),
list(x = c(10, 101, rnorm(1)), y = c(9, 10, 15)))
我一直在尝试 purrr 包,但语法对我来说是新的。
尝试过:
purrr::map(test_list, ~ .x$x[length(.x$x)]) 选择了正确的列表/深度但无法修改。
purrr::modify_depth(test_list, 2, rnorm(1))我明白为什么这选择了不正确的深度,但不知道如何更正。
到目前为止,我只能找到以简单方式操作简单列表结构的示例或我没有设法转移的复杂示例。
任何帮助都将不胜感激,总的来说,我的尝试似乎很笨拙,难以概括以供将来使用。
谢谢!
【问题讨论】: