purrr 映射到列表中的每个项目而不仅仅是列表
purrr map to each item in list not just list
我有一个 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))
您可以在一个 map
中完成另一个。您调用 max
的方式是给出该向量中所有数字的最大值,并将 0 附加到向量的末尾,因此它只给出一个值。
试试这个:使用 map_dbl
映射向量中的每个值,取 的最大值 那个单个值和 0,然后将它传递给round
.
1:3 %>%
map(~rnorm(104, .x) %>% map_dbl(max, 0) %>% round())
@camille 很好地回答了这个问题。这是在自定义函数
中使用 pmax
的替代方法
positive_round <- function(...) round(pmax(..., 0), 0)
1:3 %>%
map(~ rnorm(104, .x)) %>%
map(~positive_round(0,.x))
我有一个 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))
您可以在一个 map
中完成另一个。您调用 max
的方式是给出该向量中所有数字的最大值,并将 0 附加到向量的末尾,因此它只给出一个值。
试试这个:使用 map_dbl
映射向量中的每个值,取 的最大值 那个单个值和 0,然后将它传递给round
.
1:3 %>%
map(~rnorm(104, .x) %>% map_dbl(max, 0) %>% round())
@camille 很好地回答了这个问题。这是在自定义函数
中使用pmax
的替代方法
positive_round <- function(...) round(pmax(..., 0), 0)
1:3 %>%
map(~ rnorm(104, .x)) %>%
map(~positive_round(0,.x))