在使用purrr:map向其应用另一个函数之前,我希望按索引从列表中选择项。我试过以下几种方法,但找不到有效的方法。
require(dplyr)
require(purrr)
dat <- list(1:3,
4:6,
letters[1:3])
# I can select one item
dat[1]
# I can select two items
dat[c(1,2)]
# But how can I do this in a pipeline by index?
dat %>% map(mean)
dat %>%
filter(c(1,2)) %>%
map(mean)
dat %>%
keep(1,2) %>%
map(mean)
dat %>%
select(1,2) %>%
map(mean)
发布于 2019-05-08 02:11:27
我们可以使用`[`
dat %>%
.[c(1, 2)] %>%
map(., mean)
#[[1]]
#[1] 2
#[[2]]
#[1] 5
或者用magrittr
包的方式定义别名
extract <- `[` # literally the same as magrittr::extract
dat %>%
extract(c(1, 2)) %>%
map(., mean)
也可以写成
dat %>% `[`(c(1,2))
多亏了@Moody_Mudskipper
发布于 2019-05-08 01:41:43
一种选择是
library(tidyverse)
keep(dat, seq_along(dat) %in% 1:2) %>%
map(mean)
#[[1]]
#[1] 2
#[[2]]
#[1] 5
或map
与pluck
map(1:2, ~ pluck(dat, .x) %>%
mean)
或使用assign_in
assign_in(dat, 3, NULL) %>%
map(mean)
或者另一个选择是map_if
map_if(dat, is.numeric, mean, .else = ~ NULL) %>%
discard(is.null)
或使用discard
discard(dat, is.character) %>%
map(mean)
或者使用Filter
和map
Filter(is.numeric, dat) %>%
map(mean)
注意:它们都得到了预期的输出。
https://stackoverflow.com/questions/56037679
复制