使用purrr在相同数据上多次调用相同函数,但参数不同

问题描述 投票:0回答:1

我正在尝试对同一数据多次调用同一函数,但函数参数不同。我的问题可以描述为:

x <- as.character(1:5)
l <- list(list(name = "a", collapse = ""), list(name = "b", collapse = "-"))
output <- list()

for(l_cur in l) {
  output[[l_cur$name]] <- x %>% paste(collapse = l_cur$collapse)
}

是否有使用purrr的方法更简洁?(背景:我想将其与rvest一起使用,因为我多次在同一数据上调用html_nodes(),但只更改了css参数。)

r purrr
1个回答
1
投票

可能您可以使用:

library(purrr)
map(l, ~x %>% paste(collapse = .x$collapse)) %>% set_names(map(l, pluck, "name"))

#$a
#[1] "12345"

#$b
#[1] "1-2-3-4-5"
© www.soinside.com 2019 - 2024. All rights reserved.