【问题标题】:purrr map to each item in list not just listpurrr 映射到列表中的每个项目而不仅仅是列表
【发布时间】:2026-02-01 09:25:02
【问题描述】:

我有一个 round 函数,我想将其应用于每个列表中的每个元素,但我的代码目前对整个列表进行四舍五入。如何使用purrr 解决此问题

> library(purrr)
> library(tidy verse)
> 1:3 %>%
      map(~ rnorm(104, .x)) %>% 
      map(~ round(max(.x, 0), 0))

 [[1]]
[1] 4

[[2]]
[1] 5

[[3]]
[1] 6

如果有帮助,下面是一种非咕噜声的方法

a = sapply(rnorm(104, mean = 20, sd = 10), function(x) round(max(x, 0), 0))
b = sapply(rnorm(104, mean = 20, sd = 10), function(x) round(max(x, 0), 0))
c = sapply(rnorm(104, mean = 20, sd = 10), function(x) round(max(x, 0), 0))

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    您可以在另一个map 中执行此操作。您调用 max 的方式是给出该向量中所有数字的最大值,并将 0 附加到向量的末尾,因此它只给出一个值。

    试试这个:使用map_dbl 映射向量中的每个值,取just 单个值的最大值和0,然后将其传递给round

    1:3 %>%
        map(~rnorm(104, .x) %>% map_dbl(max, 0) %>% round())
    

    【讨论】:

      【解决方案2】:

      @camille 很好地回答了这个问题。这是在自定义函数中使用 pmax 的替代方法

      positive_round <- function(...) round(pmax(..., 0), 0)
      
      1:3 %>%
        map(~ rnorm(104, .x)) %>% 
        map(~positive_round(0,.x))
      

      【讨论】:

      • 很好,positive_round 似乎是一个方便重用的函数
      最近更新 更多