管道如何与purrr map()函数和“。” (点)符号 [英] How do pipes work with purrr map() function and the "." (dot) symbol

查看:327
本文介绍了管道如何与purrr map()函数和“。” (点)符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从purrr使用管道和map()函数时,我对数据和变量如何传递感到困惑。例如,这段代码可以像我期望的那样工作:

When using both pipes and the map() function from purrr, I am confused about how data and variables are passed along. For instance, this code works as I expect:

library(tidyverse)

cars %>% 
  select_if(is.numeric) %>% 
  map(~hist(.))

然而,当我使用ggplot进行类似的尝试时,它的表现方式很奇怪。

Yet, when I try something similar using ggplot, it behaves in a strange way.

cars %>% 
  select_if(is.numeric) %>% 
  map(~ggplot(cars, aes(.)) + geom_histogram())

我猜这是因为。在这种情况下是传递一个向量到aes(),它期望一个列名。无论哪种方式,我希望我可以使用管道和map()将每个数字列传递给ggplot函数。

I'm guessing this is because the "." in this case is passing a vector to aes(), which is expecting a column name. Either way, I wish I could pass each numeric column to a ggplot function using pipes and map(). Thanks in advance!

推荐答案

cars %>% 
  select_if(is.numeric) %>% 
  map2(., names(.), 
       ~{ggplot(data_frame(var = .x), aes(var)) + 
           geom_histogram() + 
           labs(x = .y)                    })

还有一些额外的步骤。


  • 使用 map2 而不是 map code>。第一个参数是你传递它的数据框,第二个参数是该数据框的名称的向量,所以它知道因为 ggplot 只适用于数据框,并且
  • 这还允许您访问 .y 代词来命名图。

  • Use map2 instead of map. The first argument is the dataframe you're passing it, and the second argument is a vector of the names of that dataframe, so it knows what to map over.
  • You then need to explicitly enframe your data, since ggplot only works on dataframes and coercible objects.
  • This also gives you access to the .y pronoun to name the plots.

这篇关于管道如何与purrr map()函数和“。” (点)符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆