在R studio中从函数调用生成多个绘图

在R studio中从函数调用生成多个绘图,r,ggplot2,purrr,R,Ggplot2,Purrr,我对R比较陌生。我的问题来自在线学习课程中的一个项目。我使用R studio从一个函数调用生成多个绘图。我想为每一列绘制一个新的图,它代表y轴,而x轴保持与月份相等。该函数在显示单个变量时起作用。但是,当我尝试使用多个列调用函数时,我会收到: “错误:已分析多个表达式” 类似的代码在在线程序的模拟平台上工作 我在下面提供了我的代码以及数据框中的一个小示例。可以用这种方法导出多个图吗?如果是这样,如何更新或更正代码以绘制每列的曲线图 month <- c('mar', 'oct', 'oct

我对R比较陌生。我的问题来自在线学习课程中的一个项目。我使用R studio从一个函数调用生成多个绘图。我想为每一列绘制一个新的图,它代表y轴,而x轴保持与月份相等。该函数在显示单个变量时起作用。但是,当我尝试使用多个列调用函数时,我会收到:

“错误:已分析多个表达式”

类似的代码在在线程序的模拟平台上工作

我在下面提供了我的代码以及数据框中的一个小示例。可以用这种方法导出多个图吗?如果是这样,如何更新或更正代码以绘制每列的曲线图

month <- c('mar', 'oct', 'oct')
day <- c('fri', 'tue', 'sat')
FFMC <- c(86.2, 90.6, 90.6)
DMC <- c(26.2, 35.4, 43.7)
DC <- c(94.3, 669.1, 686.9)
ISI <- c(5.1, 6.7, 6.7)
temp <- c(8.2, 18.0, 14.6)
RH <- c(51, 33, 33)
wind <- c(6.7, 0.9, 1.3)
rain <- c(0.0, 0.0, 0.0)

forestfires_df <- data.frame(month, day, FFMC, DMC, DC, ISI, temp, RH, wind, rain)

library(ggplot2)
library(purrr)

month_box <- function(x , y) {
  ggplot(data = forestfires_df, aes_string(x = month, y = y_var)) + 
    geom_boxplot() +
    theme_bw()
}

month <- names(forestfires_df)[1]
y_var <- names(forestfires_df)[3:10]

month_plots <- map2(month, y_var, month_box) 

#After running month_plots I receive "Error: More than one expression parsed"

month问题在于函数参数应该与内部参数匹配

month_box <- function(x , y) {
   ggplot(data = forestfires_df, aes_string(x = x, y = y)) + 
   geom_boxplot() +
   theme_bw()
 }
或者使用匿名函数

map2(month, y_var, ~ month_box(.x, .y))

正如我在评论中提到的,
aes\u string
已被软性弃用,取而代之的是。您可以将函数重写为一个简单的基于tidyeval的函数,然后像使用大多数其他tidyverse函数那样映射通过裸列名或其位置的感兴趣的列

有几种方法可以编写这样的函数。较旧的方法是使用QUOSRES和不带引号的列,但其语法可能会令人困惑
dplyr
附带了一个非常深入的小插曲,但我喜欢作为快速指南

month_box_quo <- function(x, y) {
  x_var <- enquo(x)
  y_var <- enquo(y)
  ggplot(forestfires_df, aes(x = !!x_var, y = !!y_var)) +
    geom_boxplot()
}
或在
和列位置使用
map\u(或使用
vars()
):

{{}}
或curly-curly)更容易理解,并返回与上面相同的绘图列表

month_box_curly <- function(x, y) {
  ggplot(forestfires_df, aes(x = {{ x }}, y = {{ y }})) +
    geom_boxplot()
}

month\u box\u curly值得注意的是,
aes\u string
早在一段时间前就被软性弃用,而支持在编写函数时使用tidyeval。
month_box_quo(x = month, y = DMC)
# mapped over variables of interest; assumes y gets the mapped-over column
map_at(forestfires_df, 3:10, month_box_quo, x = month)
# or with formula shorthand
map_at(forestfires_df, 3:10, ~month_box_quo(x = month, y = .))
month_box_curly <- function(x, y) {
  ggplot(forestfires_df, aes(x = {{ x }}, y = {{ y }})) +
    geom_boxplot()
}