r - 如何使用 purrr::pmap 调用 R 中的用户定义函数

标签 r list user-defined-functions purrr

我想使用 purrr 库的 mappmap 调用函数 wrap_vr

首先,我不明白为什么必须使用 df$v1 和 df$v2 将变量传递给函数。为什么不只使用 v1v2

第二,当我尝试使用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/

相关文章:

Python:将单个元素与列表中的每个元素配对

sql-server - 将两列转换为键值 json 对象?

R 将命名列表取消列出为一个字符串,并保留列表名称

r - 使用 DBI :dbConnect in R 连接到 SQL Server 时出现问题

r - data.frame : locations of NAs and much more 的视觉结构

R:对于两个数据框共享的列中的给定变量值,将数据框 x 中的行名称与数据框 y 中的列名称进行匹配

list - 应用窗口函数来获取递归列表,我该怎么办?

scala - 分解 Spark SQL 表中的多列

c# - 在 SQL CLR 中访问 COM

r - 如何自定义 ggplotly 对象中的悬停信息?