-1
id_data bras         Time               `Dose of estradiol`
   <chr>   <chr>        <fct>                            <dbl>
 1 16_     Progesterone Estradiol at S5-S6                588 
 2 16_     Progesterone Estradiol at S7-S8                318 
 3 16_     Progesterone Estradiol at D HCG                 43 
 4 20_     Progesterone Estradiol at S5-S6                468.
 5 20_     Progesterone Estradiol at S7-S8                470.
 6 20_     Progesterone Estradiol at D HCG                395 
 7 22_     Progesterone Estradiol at S5-S6                108 
 8 22_     Progesterone Estradiol at S7-S8                108 
 9 22_     Progesterone Estradiol at D HCG                108 
10 24_     Progesterone Estradiol at S5-S6               1369 

That is head 10 of my dataset I want to make a boxplot with ggplot

gplot(base_c_e2_anova_Prog, aes_string(x="Time", y= "Dose of estradiol"))+
  geom_boxplot(fill="#00AFBB")+
  labs(title = "title")

I want the names of my two variables to be in quotes as the ggplot should be in a function() and the names of the two variables (x, y) must be in quotes.

I don't know why aes_string doesn't work.

That is the error message:

Error in parse(text = elt) : <text>:1:6: unexpected symbol
1: Dose of
         ^
Seydou GORO
  • 1,147
  • 7
  • 13
  • 1
    Relevant on coding with `aes()`: https://ggplot2.tidyverse.org/articles/ggplot2-in-packages.html#using-aes-and-vars-in-a-package-function – teunbrand Oct 17 '22 at 12:01
  • Thank you. It is very useful documentation – Seydou GORO Oct 17 '22 at 12:10
  • Try to use standard column names. It is not recommended to have spaces in column names. Rename `Dose of estradiol` to something like `Dose_of_estradiol`. Also `aes_string` has been deprecated. Relevant : https://stackoverflow.com/questions/63734097/why-do-i-have-to-use-aes-string-with-ggplot-in-shiny – Ronak Shah Oct 17 '22 at 12:14
  • 1
    "the ggplot should be in a function() and the names of the two variables (x, y) must be in quotes". Not so. @AndS. has given you more detail. – Limey Oct 17 '22 at 12:15

1 Answers1

1

I personally would avoid aes_string. If you want to make a function that takes a variable as an input and plots it, there are several methods that work with aes.

library(tidyverse)

plot_fun_no_quotes <- function(y){
  ggplot(mtcars, aes(as.factor(cyl), {{y}}))+
    geom_boxplot()
}
plot_fun_no_quotes(mpg) #correct

plot_fun_no_quotes("mpg") #incorrect

plot_fun_with_quotes <- function(y){
  ggplot(mtcars, aes(as.factor(cyl), !!sym(y)))+
    geom_boxplot()
}
plot_fun_with_quotes("mpg") #correct

plot_fun_with_quotes(mpg) #incorrect
#> Error in `sym()`:
#> ! Can't convert a <tbl_df/tbl/data.frame> object to a symbol.
AndS.
  • 7,748
  • 2
  • 12
  • 17