[SOLVED] Use ggplot in an R function with three inputs: filename of dataframe, and two column variables of numeric data

Issue

I would like to create an R function that takes as input:

  • a dataframe of my choosing
  • two columns of the dataframe containing numeric data

The output should be a scatterplot of one column variable against another, using both base R plot function and ggplot.

Here is a toy dataframe:

df <- data.frame("choco" = 1:5,
                 "tea" = c(2,4,5,8,10),
                 "coffee" = c(0.5,2,3,1.5,2.5),
                 "sugar" = 16:20)

Here is the function I wrote, which doesn’t work (also tried this with base R plot which didn’t work – code not shown)

test <- function(Data, ing1, ing2)  {
  ggplot(Data, aes(x = ing1, y = ing2)) +
    geom_point()
}
test(Data = df, ing1 = "choco", ing2 = "tea")

As part of the above function, I would like to incorporate an ‘if..else’ statement to test whether ing1 and ing2 inputs are valid, e.g.:

try(test("coffee", "mint"))
  • the above inputs should prompt a message that ‘one or both of the inputs is not valid’
    I can see that using %in% could be the right way to do this, but I’m unsure of the syntax.

Solution

df <- data.frame(
  "choco" = 1:5,
  "tea" = c(2, 4, 5, 8, 10),
  "coffee" = c(0.5, 2, 3, 1.5, 2.5),
  "sugar" = 16:20
)

test <- function(Data, ing1, ing2)  {
  if (ing1 %in% names(Data)  &  ing2 %in% names(Data)) {
    ggplot(Data, aes(x = Data[, ing1], y = Data[, ing2])) +
      geom_point()
  }
  else {
    print("Both ing1, and ing2 has to be columns of data frame")
  }
}
test(Data = df, ing1 = "choco", ing2 = "sugar")

Regards,
Grzegorz

Answered By – Grzegorz Sapijaszko

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.