0

I am trying to create a boxplot where on the x axis there is a binary 1/2 variable. When I create my boxplot and the loop using ggplot I just get one big boxplot that is centered at 1.5 when instead I want a boxplot at 1 and a boxplot at 2. I am new to this so any help and additional reading would be appreciated. Below is the code.

myboxplot <- function(mydata=ivf_dataset, myexposure, myoutcome  )
  {
  bp <- ggplot(mydata, aes_(as.name(myexposure), as.name(myoutcome))) +
     geom_boxplot() 
      print(bp)
  }
 myboxplot(myexposure = "ART_CURRENT", myoutcome = "H19_DMR_mean")
Dillon Lloyd
  • 125
  • 1
  • 11
  • See also these answers https://stackoverflow.com/a/50726130/786542 & https://stackoverflow.com/a/49870618/786542 – Tung Jun 11 '18 at 18:29

2 Answers2

0
myboxplot <- function(mydata=ivf_dataset, myexposure, myoutcome  )
  {
  bp <- ggplot(mydata, aes_(myexposure, as.factor(myoutcome))) +
     geom_boxplot() 
      print(bp)
  }
 myboxplot(myexposure = "ART_CURRENT", myoutcome = "H19_DMR_mean")

If you want to plot multiple boxplot based on the value of a variable, that variable must be a factor!

Seymour
  • 3,104
  • 2
  • 22
  • 46
0

The following will do what you want.
The trick is to get the values of the variables you want to plot, since you pass them to the function as character strings.

library(ggplot2)

set.seed(7153)
ivf_dataset <- data.frame(
  ART_CURRENT = sample.int(2, 100, TRUE),
  H19_DMR_mean = rnorm(100)
)

myboxplot <- function(mydata=ivf_dataset, myexposure, myoutcome  ){
  bp <- ggplot(mydata, aes(x = as.factor(get(myexposure)), y = get(myoutcome))) +
    geom_boxplot() 
  print(bp)
}
myboxplot(myexposure = "ART_CURRENT", myoutcome = "H19_DMR_mean")

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thank you, that does work however do you have any good readings on how the "get" function works? – Dillon Lloyd Jun 11 '18 at 16:55
  • @DillonLloyd Well, there is `help("get")` and the source code, R is open source. But I must admit to never having read it (the source). – Rui Barradas Jun 11 '18 at 18:00