r - 如何使用 purrr::pmap 在 R 中调用用户定义的函数
问题描述
我想wrap_vr
使用map
或调用库pmap
的purrr
函数。
首先,我不明白为什么我必须使用df$v1
并将df$v2
变量传递给函数。为什么不v1
,v2
只有?
其次,当我尝试使用时我的错误是什么pmap
?
library(tidyverse)
df <- tibble(cy = c('a', 'a', 'b', 'b'),
date = c(1,2,1,2),
v1 = c(1,2,3,1),
v2 = c(5,3,2,1))
wrap_vr <- function(df, vr, tit, ylab){
ggplot(data = df, aes(date, all_of(vr))) +
geom_line(color = "steelblue", size = 1) +
labs(title = tit,
y = ylab, x = "") +
facet_wrap(~ cy)
}
wrap_vr(df, df$v1, "title_1", "ylabel_1")
wrap_vr(df, df$v2, "title_2", "ylabel_2")
list_1 <- list(df, list(df$v1, df$v2), list("title_1", "title_2"), list("ylabel_1", "ylabel_2"))
# This gives an error
pmap(list_1, ~wrap_vr(.x))
#> Error: Element 2 of `.l` must have length 1 or 4, not 2
Created on 2021-07-06 by the reprex package (v2.0.0)
解决方案
更改代码中的一些内容可以解决此问题。首先,您的数据集不应作为列表读取,因此您可以将其从list_1
.
list_1 <- list(list(df$v1, df$v2), list("title_1", "title_2"), list("ylabel_1", "ylabel_2"))
从那里,您可以像这样表达您的 pmap 调用以获得您所追求的结果:
pmap(list_1, ~wrap_vr(df, ..1, ..2, ..3))