管道如何使用purrr map()函数和“。”(点)符号

问题描述 投票:5回答:2

当使用purrr的两个管道和map()函数时,我对数据和变量的传递方式感到困惑。例如,此代码按预期工作:

library(tidyverse)

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

然而,当我尝试使用ggplot类似的东西时,它表现得很奇怪。

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

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

r ggplot2 dplyr tidyverse purrr
2个回答
8
投票
cars %>% 
  select_if(is.numeric) %>% 
  map2(., names(.), 
       ~{ggplot(data_frame(var = .x), aes(var)) + 
           geom_histogram() + 
           labs(x = .y)                    })

# Alternate version
cars %>% 
  select_if(is.numeric) %>% 
  imap(.,
       ~{ggplot(data_frame(var = .x), aes(var)) + 
           geom_histogram() + 
           labs(x = .y)                    })

enter image description here

enter image description here

还有一些额外的步骤。

  • 使用map2而不是map。第一个参数是您传递的数据帧,第二个参数是该数据帧的names的向量,因此它知道map的结果。 (或者,imap(x, ...)map2(x, names(x), ...)的同义词。它是一个“索引图”,因此是“imap”。)。
  • 然后,您需要显式地对数据进行enframe,因为ggplot仅适用于数据帧和可强制对象。
  • 这也使您可以访问.y代名词来命名这些情节。

9
投票

您不应该将原始数据传递给美学映射。相反,您应该动态构建data.frame。例如

cars %>% 
  select_if(is.numeric) %>% 
  map(~ggplot(data_frame(x=.), aes(x)) + geom_histogram())
© www.soinside.com 2019 - 2024. All rights reserved.