【问题标题】:Modifying specified list elements r修改指定的列表元素 r
【发布时间】: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 &lt;- 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))我明白为什么这选择了不正确的深度,但不知道如何更正。

到目前为止,我只能找到以简单方式操作简单列表结构的示例或我没有设法转移的复杂示例。

任何帮助都将不胜感激,总的来说,我的尝试似乎很笨拙,难以概括以供将来使用。

谢谢!

【问题讨论】:

    标签: r list tidyverse purrr


    【解决方案1】:

    在基础 R 中,您可以使用 Map

    示例 1

    z <- c(10, 50, 6, 12)
    Map(function(v, w) { v$x <- replace(v$x, 3, w); v; }, test_list, z)
    #[[1]]
    #[[1]]$x
    #[1]  10 101  10
    #
    #[[1]]$y
    #[1]  9 12 11
    #
    #
    #[[2]]
    #[[2]]$x
    #[1]  10 133  50
    #
    #[[2]]$y
    #[1]  9 15 13
    #
    #
    #[[3]]
    #[[3]]$x
    #[1]  10 101   6
    #
    #[[3]]$y
    #[1]  9 18 11
    #
    #
    #[[4]]
    #[[4]]$x
    #[1]  10 101  12
    #
    #[[4]]$y
    #[1]  9 10 15
    

    示例 2

    Map(function(v, w) { v$x <- replace(v$x, 3, w); v; }, test_list, rnorm(length(test_list)))
    

    或者同样使用purrr::map2

    purrr::map2(test_list, z, function(v, w) { v$x <- replace(v$x, 3, w); v; })
    purrr::map2(test_list, rnorm(length(test_list)), function(v, w) { v$x <- replace(v$x, 3, w); v; })
    

    【讨论】:

    • 太棒了,感谢您的超快速回复!代码中的一些新细节我也可以学习如何使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多