【问题标题】:Pass name through `map()` to be evaluated lazily通过 `map()` 传递名称以进行延迟评估
【发布时间】:2019-08-01 01:23:06
【问题描述】:

我正在以编程方式制作一系列图,我想将小标题(或数据框)的名称传递到我的 ggplot2 图的标题中,所以我知道哪个是哪个。

deparse(substitute(x)) 用于从 tibble 制作单个图,但在通过 purrr::map() 从 tibble 列表制作图时输出 "."

#initialize data frame
myDf <- tibble(x = LETTERS[1:5], y = sample(1:10, 5))

#initialize function
myPlot <- function(df) {
    title = deparse(substitute(df))
    ggplot(df, aes(x, y)) +
        geom_col() +
        ggtitle(title)
}

#call function
myPlot(myDf)

这给了我一个标题为myDF 的情节。

现在我想对一系列地块做同样的事情:

#initialize list of data frames
myDFs <- vector("list", 0)
myDFs$first  <- tibble(x = LETTERS[1:5], y = sample(1:10, 5))
myDFs$second <- tibble(x = LETTERS[1:5], y = sample(1:10, 5))
myDFs$third  <- tibble(x = LETTERS[1:5], y = sample(1:10, 5))

#initialize same function
myPlot <- function(df) {
    title = deparse(substitute(df))
    ggplot(df, aes(x, y)) +
        geom_col() +
        ggtitle(title)
}

#call function with purrr::map
map(myDFs, myPlot)

现在每个标题都使用相同的标题:.x[[i]]

我很想知道如何通过地图传递信息量更大的标题。不一定要漂亮,但一定要独特。提前谢谢!

【问题讨论】:

    标签: r ggplot2 lazy-evaluation purrr


    【解决方案1】:

    我们可以使用为此类操作而设计的imap

    myPlot <- function(df, names) {
      ggplot(df, aes(x, y)) +
       geom_col() +
       ggtitle(names)
    }
    
    purrr::imap(myDFs, myPlot)
    

    【讨论】:

      【解决方案2】:

      我们可以使用来自base RMap

      Map(myPlot, myDFs, names(myDFs))
      

      或者使用iwalk

      purrr::iwalk(myDFs, ~ myPlot(.x, .y))
      

      在哪里

      myPlot <- function(data, nameVec){
          ggplot(data, aes(x, y)) +
            geom_col() +
            ggtitle(nameVec)
       }
      

      【讨论】:

      • 感谢您向我展示步行功能!为了尝试它,我不得不稍微更新我的函数以保存绘图,然后将其打印在单独的行上,但不让它显示在屏幕上真是太好了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      相关资源
      最近更新 更多