我想使用 purrr
库的 map
或 pmap
调用函数 wrap_vr
。
首先,我不明白为什么必须使用 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))
关于r - 如何使用 purrr::pmap 调用 R 中的用户定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68272622/